Files
usb-server/driver/windows/driver.c
T
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

285 lines
9.0 KiB
C

/*
* usbshare - driver entry, device setup and claim lifecycle
*/
#include "usbshare.h"
NTSTATUS
DriverEntry(
_In_ PDRIVER_OBJECT DriverObject,
_In_ PUNICODE_STRING RegistryPath
)
{
WDF_DRIVER_CONFIG config;
NTSTATUS status;
WDF_DRIVER_CONFIG_INIT(&config, UsbShareEvtDeviceAdd);
status = WdfDriverCreate(DriverObject, RegistryPath,
WDF_NO_OBJECT_ATTRIBUTES, &config, WDF_NO_HANDLE);
if (!NT_SUCCESS(status)) {
KdPrint(("usbshare: WdfDriverCreate failed 0x%x\n", status));
}
return status;
}
NTSTATUS
UsbShareEvtDeviceAdd(
_In_ WDFDRIVER Driver,
_Inout_ PWDFDEVICE_INIT DeviceInit
)
{
NTSTATUS status;
WDFDEVICE device;
WDF_OBJECT_ATTRIBUTES attributes;
WDF_PNPPOWER_EVENT_CALLBACKS pnpCallbacks;
WDF_FILEOBJECT_CONFIG fileConfig;
WDF_IO_QUEUE_CONFIG queueConfig;
PDEVICE_CONTEXT context;
WDFQUEUE queue;
UNREFERENCED_PARAMETER(Driver);
/*
* Declaring ourselves a filter is what makes this driver safe to attach
* to arbitrary devices: the framework then forwards every request we do
* not explicitly handle to the driver below, so a device we know nothing
* about keeps working exactly as before.
*/
WdfFdoInitSetFilter(DeviceInit);
WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&pnpCallbacks);
pnpCallbacks.EvtDevicePrepareHardware = UsbShareEvtDevicePrepareHardware;
WdfDeviceInitSetPnpPowerEventCallbacks(DeviceInit, &pnpCallbacks);
/*
* File create and close callbacks give us the claim lifecycle: a claim is
* tied to a handle, so when the client exits — cleanly or not — the
* kernel closes the handle and the device goes back to its class driver.
* Without this a crashed client would leave hardware unusable until
* reboot.
*/
WDF_FILEOBJECT_CONFIG_INIT(&fileConfig,
UsbShareEvtDeviceFileCreate,
UsbShareEvtFileClose,
WDF_NO_EVENT_CALLBACK); /* no cleanup callback */
WdfDeviceInitSetFileObjectConfig(DeviceInit, &fileConfig,
WDF_NO_OBJECT_ATTRIBUTES);
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, DEVICE_CONTEXT);
status = WdfDeviceCreate(&DeviceInit, &attributes, &device);
if (!NT_SUCCESS(status)) {
KdPrint(("usbshare: WdfDeviceCreate failed 0x%x\n", status));
return status;
}
context = GetDeviceContext(device);
RtlZeroMemory(context, sizeof(DEVICE_CONTEXT));
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
attributes.ParentObject = device;
status = WdfSpinLockCreate(&attributes, &context->ClaimLock);
if (!NT_SUCCESS(status)) {
return status;
}
status = WdfSpinLockCreate(&attributes, &context->PendingLock);
if (!NT_SUCCESS(status)) {
return status;
}
status = WdfCollectionCreate(&attributes, &context->PendingTransfers);
if (!NT_SUCCESS(status)) {
return status;
}
/*
* Default queue. Requests we do not recognise are forwarded down by the
* framework because this is a filter device.
*/
WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&queueConfig, WdfIoQueueDispatchParallel);
queueConfig.EvtIoDeviceControl = UsbShareEvtIoDeviceControl;
queueConfig.EvtIoInternalDeviceControl = UsbShareEvtIoInternalDeviceControl;
queueConfig.EvtIoDefault = UsbShareEvtIoDefault;
status = WdfIoQueueCreate(device, &queueConfig, WDF_NO_OBJECT_ATTRIBUTES, &queue);
if (!NT_SUCCESS(status)) {
KdPrint(("usbshare: WdfIoQueueCreate failed 0x%x\n", status));
return status;
}
/* Publish the interface so user mode can find this device. */
status = WdfDeviceCreateDeviceInterface(device, &GUID_DEVINTERFACE_USBSHARE, NULL);
if (!NT_SUCCESS(status)) {
KdPrint(("usbshare: WdfDeviceCreateDeviceInterface failed 0x%x\n", status));
return status;
}
return STATUS_SUCCESS;
}
NTSTATUS
UsbShareEvtDevicePrepareHardware(
_In_ WDFDEVICE Device,
_In_ WDFCMRESLIST ResourcesRaw,
_In_ WDFCMRESLIST ResourcesTranslated
)
{
NTSTATUS status;
PDEVICE_CONTEXT context = GetDeviceContext(Device);
WDF_USB_DEVICE_CREATE_CONFIG createConfig;
USB_DEVICE_DESCRIPTOR deviceDescriptor;
WDF_USB_DEVICE_SELECT_CONFIG_PARAMS configParams;
UCHAR i;
UNREFERENCED_PARAMETER(ResourcesRaw);
UNREFERENCED_PARAMETER(ResourcesTranslated);
/* PrepareHardware can run more than once across power transitions. */
if (context->UsbDevice != NULL) {
return STATUS_SUCCESS;
}
WDF_USB_DEVICE_CREATE_CONFIG_INIT(&createConfig, USBD_CLIENT_CONTRACT_VERSION_602);
status = WdfUsbTargetDeviceCreateWithParameters(Device, &createConfig,
WDF_NO_OBJECT_ATTRIBUTES,
&context->UsbDevice);
if (!NT_SUCCESS(status)) {
KdPrint(("usbshare: WdfUsbTargetDeviceCreateWithParameters failed 0x%x\n", status));
return status;
}
WdfUsbTargetDeviceGetDeviceDescriptor(context->UsbDevice, &deviceDescriptor);
context->Info.VendorId = deviceDescriptor.idVendor;
context->Info.ProductId = deviceDescriptor.idProduct;
context->Info.BcdDevice = deviceDescriptor.bcdDevice;
context->Info.DeviceClass = deviceDescriptor.bDeviceClass;
context->Info.DeviceSubClass = deviceDescriptor.bDeviceSubClass;
context->Info.DeviceProtocol = deviceDescriptor.bDeviceProtocol;
context->Info.NumConfigurations = deviceDescriptor.bNumConfigurations;
context->Info.ConfigurationValue = 1;
/*
* Select a configuration so pipe handles become available.
*
* This is the part most likely to need adjusting: on a device the class
* driver has already configured, selecting again may be redundant or
* disruptive. A more careful implementation would query the current
* configuration first and only select if none is active.
*/
WDF_USB_DEVICE_SELECT_CONFIG_PARAMS_INIT_SINGLE_INTERFACE(&configParams);
status = WdfUsbTargetDeviceSelectConfig(context->UsbDevice,
WDF_NO_OBJECT_ATTRIBUTES,
&configParams);
if (!NT_SUCCESS(status)) {
KdPrint(("usbshare: WdfUsbTargetDeviceSelectConfig failed 0x%x\n", status));
/*
* Not fatal: without pipes only control transfers work, but the
* filter must not break the device for the class driver either way.
*/
return STATUS_SUCCESS;
}
context->UsbInterface = configParams.Types.SingleInterface.ConfiguredUsbInterface;
/* Map pipes by full endpoint address. */
{
BYTE pipeCount = configParams.Types.SingleInterface.NumberConfiguredPipes;
for (i = 0; i < pipeCount; i++) {
WDF_USB_PIPE_INFORMATION pipeInfo;
WDFUSBPIPE pipe;
WDF_USB_PIPE_INFORMATION_INIT(&pipeInfo);
pipe = WdfUsbInterfaceGetConfiguredPipe(context->UsbInterface, i, &pipeInfo);
if (pipe != NULL) {
context->Pipes[pipeInfo.EndpointAddress] = pipe;
/*
* Let short reads through. Without this a transfer that
* returns fewer bytes than requested fails, which is normal
* and expected for interrupt endpoints.
*/
WdfUsbTargetPipeSetNoMaximumPacketSizeCheck(pipe);
}
}
}
return STATUS_SUCCESS;
}
VOID
UsbShareEvtDeviceFileCreate(
_In_ WDFDEVICE Device,
_In_ WDFREQUEST Request,
_In_ WDFFILEOBJECT FileObject
)
{
UNREFERENCED_PARAMETER(Device);
UNREFERENCED_PARAMETER(FileObject);
/* Opening the handle is always allowed; claiming is a separate step. */
WdfRequestComplete(Request, STATUS_SUCCESS);
}
VOID
UsbShareEvtFileClose(
_In_ WDFFILEOBJECT FileObject
)
{
WDFDEVICE device = WdfFileObjectGetDevice(FileObject);
PDEVICE_CONTEXT context = GetDeviceContext(device);
/*
* The safety net: if this handle held the claim, give the device back.
* This runs whether the client exited cleanly or was killed.
*/
UsbShareReleaseClaim(context, FileObject);
}
BOOLEAN
UsbShareIsClaimed(
_In_ PDEVICE_CONTEXT Context
)
{
BOOLEAN claimed;
WdfSpinLockAcquire(Context->ClaimLock);
claimed = Context->Claimed;
WdfSpinLockRelease(Context->ClaimLock);
return claimed;
}
VOID
UsbShareReleaseClaim(
_In_ PDEVICE_CONTEXT Context,
_In_opt_ WDFFILEOBJECT Owner
)
{
BOOLEAN released = FALSE;
WdfSpinLockAcquire(Context->ClaimLock);
/*
* With an owner given, only that owner may release — otherwise closing an
* unrelated handle would hand the device back while a client is using it.
*/
if (Context->Claimed && (Owner == NULL || Context->ClaimOwner == Owner)) {
Context->Claimed = FALSE;
Context->ClaimOwner = NULL;
released = TRUE;
}
WdfSpinLockRelease(Context->ClaimLock);
if (released) {
KdPrint(("usbshare: device released\n"));
}
}