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>
164 lines
4.5 KiB
Go
164 lines
4.5 KiB
Go
package crypto
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"encoding/binary"
|
|
"errors"
|
|
"fmt"
|
|
"sync"
|
|
)
|
|
|
|
// Frame layout on the wire:
|
|
//
|
|
// [8 bytes counter (big endian)][ciphertext + 16 byte auth tag]
|
|
//
|
|
// The counter travels in the clear because the receiver needs it to rebuild
|
|
// the nonce; it carries no secret, and the authentication tag covers it.
|
|
const (
|
|
counterSize = 8
|
|
nonceSize = 12 // AES-GCM standard nonce
|
|
tagSize = 16
|
|
// FrameOverhead is how much a frame grows over its plaintext.
|
|
FrameOverhead = counterSize + tagSize
|
|
)
|
|
|
|
// Direction distinguishes the two halves of a tunnel.
|
|
//
|
|
// Both ends derive the same tunnel key, so without this they would encrypt
|
|
// different plaintexts under the same (key, nonce) pair — the one failure that
|
|
// breaks AES-GCM completely, revealing the XOR of both messages and allowing
|
|
// forgery.
|
|
type Direction uint8
|
|
|
|
const (
|
|
// DirShareToUse marks traffic from the sharing side to the using side.
|
|
DirShareToUse Direction = 1
|
|
// DirUseToShare marks traffic in the opposite direction.
|
|
DirUseToShare Direction = 2
|
|
)
|
|
|
|
// ErrCounterExhausted is returned once a sealer has used every counter value.
|
|
var ErrCounterExhausted = errors.New("tunnel counter exhausted, reconnect required")
|
|
|
|
// ErrReplay is returned for a frame whose counter was already seen.
|
|
var ErrReplay = errors.New("replayed or out-of-order tunnel frame")
|
|
|
|
// Sealer encrypts outgoing tunnel frames.
|
|
type Sealer struct {
|
|
mu sync.Mutex
|
|
aead cipher.AEAD
|
|
dir Direction
|
|
counter uint64
|
|
}
|
|
|
|
// Opener decrypts incoming tunnel frames.
|
|
type Opener struct {
|
|
mu sync.Mutex
|
|
aead cipher.AEAD
|
|
dir Direction
|
|
lastSeen uint64
|
|
started bool
|
|
}
|
|
|
|
// NewSealer creates a sealer for one direction of a tunnel.
|
|
func NewSealer(key []byte, dir Direction) (*Sealer, error) {
|
|
aead, err := newAEAD(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &Sealer{aead: aead, dir: dir}, nil
|
|
}
|
|
|
|
// NewOpener creates an opener for one direction of a tunnel.
|
|
// The direction must be the one the *sender* used.
|
|
func NewOpener(key []byte, dir Direction) (*Opener, error) {
|
|
aead, err := newAEAD(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &Opener{aead: aead, dir: dir}, nil
|
|
}
|
|
|
|
func newAEAD(key []byte) (cipher.AEAD, error) {
|
|
if len(key) != keySize {
|
|
return nil, fmt.Errorf("key is %d bytes, want %d", len(key), keySize)
|
|
}
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("creating cipher: %w", err)
|
|
}
|
|
aead, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("creating GCM: %w", err)
|
|
}
|
|
return aead, nil
|
|
}
|
|
|
|
// nonceFor builds the 12-byte nonce: direction, four zero bytes, counter.
|
|
// Distinct directions therefore never share a nonce under the same key.
|
|
func nonceFor(dir Direction, counter uint64) [nonceSize]byte {
|
|
var nonce [nonceSize]byte
|
|
nonce[0] = byte(dir)
|
|
binary.BigEndian.PutUint64(nonce[4:], counter)
|
|
return nonce
|
|
}
|
|
|
|
// Seal encrypts one frame and returns it ready for transmission.
|
|
func (s *Sealer) Seal(plaintext []byte) ([]byte, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
if s.counter == ^uint64(0) {
|
|
return nil, ErrCounterExhausted
|
|
}
|
|
counter := s.counter
|
|
s.counter++
|
|
|
|
nonce := nonceFor(s.dir, counter)
|
|
|
|
out := make([]byte, counterSize, counterSize+len(plaintext)+tagSize)
|
|
binary.BigEndian.PutUint64(out, counter)
|
|
|
|
// The counter prefix is authenticated as additional data, so it cannot be
|
|
// altered to make a frame decrypt under a different nonce.
|
|
return s.aead.Seal(out, nonce[:], plaintext, out[:counterSize]), nil
|
|
}
|
|
|
|
// Open decrypts one frame.
|
|
//
|
|
// Frames must arrive in order, which holds for both transports in use: a
|
|
// direct TCP connection and a relayed WebSocket both preserve ordering. A
|
|
// counter that does not advance means duplication or tampering.
|
|
func (o *Opener) Open(frame []byte) ([]byte, error) {
|
|
if len(frame) < FrameOverhead {
|
|
return nil, fmt.Errorf("frame is %d bytes, minimum is %d", len(frame), FrameOverhead)
|
|
}
|
|
|
|
counter := binary.BigEndian.Uint64(frame[:counterSize])
|
|
|
|
o.mu.Lock()
|
|
if o.started && counter <= o.lastSeen {
|
|
o.mu.Unlock()
|
|
return nil, ErrReplay
|
|
}
|
|
o.mu.Unlock()
|
|
|
|
nonce := nonceFor(o.dir, counter)
|
|
plaintext, err := o.aead.Open(nil, nonce[:], frame[counterSize:], frame[:counterSize])
|
|
if err != nil {
|
|
return nil, fmt.Errorf("authentication failed: %w", err)
|
|
}
|
|
|
|
// Only advance after the frame proves authentic, so a forged frame with a
|
|
// high counter cannot make us reject the genuine ones that follow.
|
|
o.mu.Lock()
|
|
if counter > o.lastSeen || !o.started {
|
|
o.lastSeen = counter
|
|
o.started = true
|
|
}
|
|
o.mu.Unlock()
|
|
|
|
return plaintext, nil
|
|
}
|