Files
usb-server/internal/usb/descriptors_test.go
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

239 lines
7.7 KiB
Go

package usb
import "testing"
// buildDescriptorBlob assembles a device descriptor followed by raw
// configuration bytes, the way a usbdevfs file read returns them.
func buildDescriptorBlob(numConfigs uint8, configs ...[]byte) []byte {
dev := []byte{
18, // bLength
0x01, // bDescriptorType = DEVICE
0x00, 0x02, // bcdUSB 2.00
0x00, // bDeviceClass (per-interface)
0x00, // bDeviceSubClass
0x00, // bDeviceProtocol
64, // bMaxPacketSize0
0x6d, 0x04, // idVendor 046d
0x1c, 0xc0, // idProduct c01c
0x10, 0x02, // bcdDevice 0210
1, 2, 3, // string indices
numConfigs,
}
blob := dev
for _, c := range configs {
blob = append(blob, c...)
}
return blob
}
func ifaceDesc(number, alt, numEndpoints, class, subclass, protocol uint8) []byte {
return []byte{9, 0x04, number, alt, numEndpoints, class, subclass, protocol, 0}
}
func endpointDesc(addr, attrs uint8, maxPacket uint16, interval uint8) []byte {
return []byte{7, 0x05, addr, attrs, byte(maxPacket), byte(maxPacket >> 8), interval}
}
func configDesc(value uint8, body []byte) []byte {
total := 9 + len(body)
cfg := []byte{9, 0x02, byte(total), byte(total >> 8), 1, value, 0, 0x80, 250}
return append(cfg, body...)
}
func TestParseDescriptorsDeviceFields(t *testing.T) {
blob := buildDescriptorBlob(1, configDesc(1, ifaceDesc(0, 0, 0, 3, 1, 1)))
pd, err := ParseDescriptors(blob)
if err != nil {
t.Fatalf("ParseDescriptors: %v", err)
}
if pd.VendorID != 0x046d {
t.Errorf("VendorID = %04x, want 046d", pd.VendorID)
}
if pd.ProductID != 0xc01c {
t.Errorf("ProductID = %04x, want c01c", pd.ProductID)
}
if pd.BcdDevice != 0x0210 {
t.Errorf("BcdDevice = %04x, want 0210", pd.BcdDevice)
}
if pd.NumConfigs != 1 {
t.Errorf("NumConfigs = %d, want 1", pd.NumConfigs)
}
if len(pd.Configs) != 1 {
t.Fatalf("got %d configs, want 1", len(pd.Configs))
}
}
// A composite device where endpoint number 1 appears twice with different
// directions and different transfer types. Keying the endpoint map by number
// alone collapses these two into one, which is what made the server submit
// interrupt URBs with the bulk type and broke HID devices.
func TestAllEndpointsKeepsDirectionsSeparate(t *testing.T) {
body := ifaceDesc(0, 0, 2, 0x08, 0x06, 0x50) // mass storage
body = append(body, endpointDesc(0x01, 0x02, 512, 0)...) // bulk OUT, EP1
body = append(body, endpointDesc(0x82, 0x02, 512, 0)...) // bulk IN, EP2
body = append(body, ifaceDesc(1, 0, 1, 0x03, 0x01, 0x01)...) // HID keyboard
body = append(body, endpointDesc(0x81, 0x03, 8, 10)...) // interrupt IN, EP1
blob := buildDescriptorBlob(1, configDesc(1, body))
pd, err := ParseDescriptors(blob)
if err != nil {
t.Fatalf("ParseDescriptors: %v", err)
}
eps := pd.Configs[0].AllEndpoints()
if len(eps) != 3 {
t.Fatalf("got %d endpoints, want 3: %+v", len(eps), eps)
}
if got := eps[0x01].TransferType; got != TransferTypeBulk {
t.Errorf("EP 0x01 type = %d, want bulk (%d)", got, TransferTypeBulk)
}
if got := eps[0x81].TransferType; got != TransferTypeInterrupt {
t.Errorf("EP 0x81 type = %d, want interrupt (%d) — direction bit must not collapse", got, TransferTypeInterrupt)
}
if got := eps[0x81].Interval; got != 10 {
t.Errorf("EP 0x81 interval = %d, want 10", got)
}
if got := eps[0x82].MaxPacketSize; got != 512 {
t.Errorf("EP 0x82 maxpacket = %d, want 512", got)
}
}
// A webcam's isochronous endpoints only exist in a non-zero alternate
// setting. sysfs shows only the active setting, so an endpoint map built from
// it would classify these as bulk after a SET_INTERFACE.
func TestAllEndpointsIncludesAlternateSettings(t *testing.T) {
body := ifaceDesc(1, 0, 0, 0x0e, 0x02, 0x00) // video streaming, alt 0: no endpoints
body = append(body, ifaceDesc(1, 1, 1, 0x0e, 0x02, 0x00)...)
body = append(body, endpointDesc(0x81, 0x05, 1024, 1)...) // isochronous IN
body = append(body, ifaceDesc(1, 2, 1, 0x0e, 0x02, 0x00)...)
body = append(body, endpointDesc(0x81, 0x05, 2048, 1)...)
blob := buildDescriptorBlob(1, configDesc(1, body))
pd, err := ParseDescriptors(blob)
if err != nil {
t.Fatalf("ParseDescriptors: %v", err)
}
cfg := pd.Configs[0]
if len(cfg.Interfaces) != 3 {
t.Fatalf("got %d interface descriptors, want 3 (alt 0,1,2)", len(cfg.Interfaces))
}
eps := cfg.AllEndpoints()
ep, ok := eps[0x81]
if !ok {
t.Fatal("EP 0x81 missing — endpoints from non-zero alternate settings were dropped")
}
if ep.TransferType != TransferTypeIsochronous {
t.Errorf("EP 0x81 type = %d, want isochronous (%d)", ep.TransferType, TransferTypeIsochronous)
}
}
func TestActiveInterfacesOnlyAltZero(t *testing.T) {
body := ifaceDesc(0, 0, 0, 0x01, 0x01, 0x00)
body = append(body, ifaceDesc(1, 0, 0, 0x01, 0x02, 0x00)...)
body = append(body, ifaceDesc(1, 1, 1, 0x01, 0x02, 0x00)...)
body = append(body, endpointDesc(0x81, 0x05, 192, 1)...)
blob := buildDescriptorBlob(1, configDesc(1, body))
pd, _ := ParseDescriptors(blob)
active := pd.Configs[0].ActiveInterfaces()
if len(active) != 2 {
t.Fatalf("got %d active interfaces, want 2 (one per interface number)", len(active))
}
for _, iface := range active {
if iface.AltSetting != 0 {
t.Errorf("interface %d has alt setting %d, want 0", iface.Number, iface.AltSetting)
}
}
}
// Class-specific descriptors (HID, UVC, audio) sit between the standard ones
// and must be skipped by bLength rather than confusing the walk.
func TestParseDescriptorsSkipsClassSpecific(t *testing.T) {
hidDesc := []byte{9, 0x21, 0x11, 0x01, 0x00, 0x01, 0x22, 0x3f, 0x00}
body := ifaceDesc(0, 0, 1, 0x03, 0x01, 0x01)
body = append(body, hidDesc...)
body = append(body, endpointDesc(0x81, 0x03, 8, 10)...)
blob := buildDescriptorBlob(1, configDesc(1, body))
pd, err := ParseDescriptors(blob)
if err != nil {
t.Fatalf("ParseDescriptors: %v", err)
}
eps := pd.Configs[0].AllEndpoints()
if _, ok := eps[0x81]; !ok {
t.Fatal("endpoint after a HID descriptor was not parsed")
}
if len(pd.Configs[0].Interfaces[0].Endpoints) != 1 {
t.Errorf("got %d endpoints on the interface, want 1",
len(pd.Configs[0].Interfaces[0].Endpoints))
}
}
func TestFindConfigSelectsByValue(t *testing.T) {
blob := buildDescriptorBlob(2,
configDesc(1, ifaceDesc(0, 0, 0, 0x03, 0, 0)),
configDesc(2, ifaceDesc(0, 0, 0, 0x08, 0, 0)),
)
pd, err := ParseDescriptors(blob)
if err != nil {
t.Fatalf("ParseDescriptors: %v", err)
}
cfg := pd.FindConfig(2)
if cfg == nil {
t.Fatal("FindConfig(2) returned nil")
}
if cfg.Interfaces[0].Class != 0x08 {
t.Errorf("got interface class %02x, want 08 — wrong configuration selected", cfg.Interfaces[0].Class)
}
if pd.FindConfig(9) != nil {
t.Error("FindConfig(9) should return nil for a configuration that does not exist")
}
}
func TestParseDescriptorsRejectsGarbage(t *testing.T) {
tests := []struct {
name string
data []byte
}{
{"empty", nil},
{"too short", []byte{18, 0x01, 0x00}},
{"not a device descriptor", append([]byte{9, 0x02}, make([]byte, 20)...)},
{"no configuration", buildDescriptorBlob(1)},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if _, err := ParseDescriptors(tt.data); err == nil {
t.Error("expected an error, got nil")
}
})
}
}
// A truncated or zero-length descriptor must terminate the walk instead of
// looping forever or reading past the buffer.
func TestParseDescriptorsHandlesTruncation(t *testing.T) {
blob := buildDescriptorBlob(1, configDesc(1, ifaceDesc(0, 0, 1, 3, 1, 1)))
blob = append(blob, 0x00, 0x05) // zero bLength would spin forever
blob = append(blob, 9, 0x04) // interface descriptor claiming 9 bytes, only 2 present
done := make(chan struct{})
go func() {
defer close(done)
if _, err := ParseDescriptors(blob); err != nil {
t.Errorf("unexpected error: %v", err)
}
}()
<-done
}