diff --git a/apps/desktop/scripts/device-probe.ts b/apps/desktop/scripts/device-probe.ts index 5d552520..74edd6b6 100644 --- a/apps/desktop/scripts/device-probe.ts +++ b/apps/desktop/scripts/device-probe.ts @@ -17,6 +17,7 @@ // pnpm --filter @ipaforge/desktop device-probe rsd-services (iOS 17.4+: the device's services inside its tunnel) // pnpm --filter @ipaforge/desktop device-probe tunnel-install [] [--mb 100] [--compare] // (iOS 17.4+: a timed upload, and an install, with every service through the tunnel; --compare: and classic) +// pnpm --filter @ipaforge/desktop device-probe rp-tunnel [--mb 20] (iOS 17.4+: the tunnel over Wi-Fi, and an upload through it) // // --direct (any device command): reach the device straight over Wi-Fi only, skipping the cable and usbmuxd. The // devices to look for are usbmuxd's and --udid; their pair records come from usbmuxd. diff --git a/apps/desktop/src/main/adapters/network/tls-psk.test.ts b/apps/desktop/src/main/adapters/network/tls-psk.test.ts new file mode 100644 index 00000000..c96c948a --- /dev/null +++ b/apps/desktop/src/main/adapters/network/tls-psk.test.ts @@ -0,0 +1,79 @@ +// IPAForge's own TLS 1.2 PSK client (packages/device) against OpenSSL's server, with the cipher suite iOS's remote +// pairing tunnel takes. It lives here because packages can't use node:tls. +import { randomBytes } from 'node:crypto' +import { createServer, type Server, type TLSSocket } from 'node:tls' + +import { afterEach, describe, expect, it } from 'vitest' + +import { connectTcp } from '@desktop/main/adapters/network/tcp-connection.ts' +import { connectTlsPsk } from '@ipaforge/device' + +const PSK = new Uint8Array(32).fill(7) + +const listen = (psk: Uint8Array): Promise<{ server: Server; port: number }> => + new Promise((resolve) => { + const server = createServer( + { + ciphers: 'PSK-AES128-GCM-SHA256', + minVersion: 'TLSv1.2', + maxVersion: 'TLSv1.2', + pskCallback: () => Buffer.from(psk) + }, + (socket: TLSSocket) => + socket.on('data', (bytes) => + socket.write(Buffer.concat([Buffer.from('echo:'), bytes])) + ) + ) + server.on('tlsClientError', () => undefined) + server.listen(0, '127.0.0.1', () => { + const address = server.address() + resolve({ + server, + port: typeof address === 'object' && address ? address.port : 0 + }) + }) + }) + +const random = (length: number) => new Uint8Array(randomBytes(length)) + +describe('TLS 1.2 PSK client', () => { + let server: Server | undefined + afterEach(() => server?.close()) + + it('completes the handshake with OpenSSL and carries data both ways', async () => { + const started = await listen(PSK) + server = started.server + const tls = await connectTlsPsk( + await connectTcp('127.0.0.1', started.port), + { + psk: PSK, + randomBytes: random + } + ) + + await tls.write(new TextEncoder().encode('CDTunnel')) + expect( + new TextDecoder().decode((await tls.read()) ?? new Uint8Array()) + ).toBe('echo:CDTunnel') + + // More than one record's worth, split by the client and reassembled by the server. + const big = new Uint8Array(40_000).fill(65) + await tls.write(big) + let received = 0 + while (received < big.length + 5) + received += (await tls.read())?.length ?? big.length + expect(received).toBeGreaterThanOrEqual(big.length) + await tls.close() + }) + + it('fails when the server holds another key', async () => { + const started = await listen(new Uint8Array(32).fill(9)) + server = started.server + await expect( + connectTlsPsk(await connectTcp('127.0.0.1', started.port), { + psk: PSK, + randomBytes: random + }) + ).rejects.toMatchObject({ code: 'device.protocol_error' }) + }) +}) diff --git a/apps/desktop/src/probes/device/commands/index.ts b/apps/desktop/src/probes/device/commands/index.ts index 815befd7..d0ec3e8c 100644 --- a/apps/desktop/src/probes/device/commands/index.ts +++ b/apps/desktop/src/probes/device/commands/index.ts @@ -20,6 +20,7 @@ import { rsdServicesCommand, tunnelInstallCommand } from '@desktop/probes/device/commands/tunnel.ts' +import { wifiTunnelCommand } from '@desktop/probes/device/commands/wifi-tunnel.ts' import type { DeviceProbe } from '@desktop/probes/device/context.ts' import type { ProbeCommands } from '@desktop/probes/shared/types.ts' @@ -39,5 +40,6 @@ export const deviceCommands = (probe: DeviceProbe): ProbeCommands => ({ 'rp-pair': remotePairCommand(probe), 'wifi-list': wifiListCommand(probe), 'rsd-services': rsdServicesCommand(probe), - 'tunnel-install': tunnelInstallCommand(probe) + 'tunnel-install': tunnelInstallCommand(probe), + 'rp-tunnel': wifiTunnelCommand(probe) }) diff --git a/apps/desktop/src/probes/device/commands/wifi-tunnel.ts b/apps/desktop/src/probes/device/commands/wifi-tunnel.ts new file mode 100644 index 00000000..0a8883dd --- /dev/null +++ b/apps/desktop/src/probes/device/commands/wifi-tunnel.ts @@ -0,0 +1,62 @@ +// device-probe rp-tunnel [--mb 20]: the iOS 17.4+ tunnel over Wi-Fi. It makes (or checks) the remote pairing over +// usbmuxd, then opens the tunnel with it (remote pairing on the network, IPAForge's own TLS-PSK, the CDTunnel +// handshake, the tunnel's TCP client and RSD), and times an upload through the tunnel's AFC (written, then deleted). +import type { DeviceProbe } from '@desktop/probes/device/context.ts' +import { createProbeLogger } from '@desktop/probes/shared/logger.ts' +import { createAfcClient } from '@ipaforge/device' + +const STAGING = 'PublicStaging' +const MIB = 1024 * 1024 + +export const wifiTunnelCommand = + ({ withDevice, manager, args }: DeviceProbe) => + (): Promise => + withDevice(async (handle) => { + console.log('Remote pairing (unlock the device; tap Trust if asked)…') + const { how } = await handle.remotePairing({ + onAwaitingConsent: () => + console.log(' waiting for Trust on the device') + }) + console.log(` ${how}`) + const started = Date.now() + const tunnel = await manager.openWifiTunnel(handle.device.udid) + try { + console.log( + `tunnel and RSD over Wi-Fi in ${Date.now() - started} ms, MTU ${tunnel.mtu}, ${tunnel.services.size} services` + ) + const link = await tunnel.openShim('com.apple.afc') + if (!link) throw new Error('no AFC in the tunnel') + const afc = createAfcClient(link, { + logger: createProbeLogger(), + maxMessageBytes: 64 * MIB, + writeChunkBytes: MIB, + readChunkBytes: MIB + }) + const data = new Uint8Array(MIB) + for (let offset = 0; offset < MIB; offset += 65_536) + globalThis.crypto.getRandomValues( + data.subarray(offset, offset + 65_536) + ) + const megabytes = Number(args.option('mb') ?? 20) + const payload = new Uint8Array(megabytes * MIB) + for (let offset = 0; offset < payload.length; offset += MIB) + payload.set(data, offset) + const path = `${STAGING}/ipaforge-wifi-tunnel-${Date.now()}.bin` + try { + if (!(await afc.exists(STAGING))) await afc.mkdir(STAGING) + const upload = performance.now() + await afc.writeFile(path, payload) + const seconds = (performance.now() - upload) / 1000 + console.log( + ` AFC upload: ${megabytes} MiB in ${seconds.toFixed(2)} s = ${(megabytes / seconds).toFixed(1)} MiB/s` + ) + } finally { + await afc.remove(path).catch(() => undefined) + await afc.close() + } + const stats = tunnel.stats() + console.log(` TCP: ${JSON.stringify(stats)}`) + } finally { + await tunnel.close() + } + }) diff --git a/docs/design/roadmap.md b/docs/design/roadmap.md index 1101a58d..bea19a42 100644 --- a/docs/design/roadmap.md +++ b/docs/design/roadmap.md @@ -130,8 +130,8 @@ Every feature below maps to the phases that deliver it. "Automatic" means the us - **11.2** installing through the iOS 17+ device tunnel (RSD/CoreDevice), over USB and Wi-Fi, without depending on the system's usbmuxd for Wi-Fi, and finding devices on the network - [x] **11.2a** Wi-Fi without usbmuxd: a known device found on the network (mDNS `_apple-mobdev2._tcp` from a port of IPAForge's own, matched by the iOS 26.4+ `authTag` against the pair record's HostID, or by its MAC address) and reached straight at its address (lockdown on 62078, same pairing and TLS), also on Linux without usbmuxd; its Wi-Fi connections turned on whenever a session opens; USB first, then straight over Wi-Fi (16–18 MiB/s), then usbmuxd's Wi-Fi (6.4 MiB/s); macOS Local Network permission (translated reason) and a Devices page notice when it's refused (#97) - [x] **11.2b** the tunnel over USB: CoreDeviceProxy and CDTunnel, our own IPv6 and TCP client in TypeScript (one packet per write so none share a TLS record, packets under 8 KB at MTU 8000, window scaling, retransmission with back-off, fast retransmit and partial-ACK recovery, retransmissions ahead of queued packets), HTTP/2 and XPC, RSD (the client's own Handshake first), RSDCheckin for the shims; services lockdown refuses fall back to the tunnel, and `route: "tunnel"` sends them all through it; 34 MiB/s over USB against 35.5 classic; probes `rsd-services` and `tunnel-install` (#98) - - [ ] **11.2c** the tunnel over Wi-Fi: the 11.1 remote pairing on `_remotepairing._tcp`, encrypted `createListener`, our own TLS 1.2 PSK (iOS refuses the SHA-1 suites Electron's BoringSSL has) - - [ ] **11.2d** connection states in the UI, recovery and docs + - [x] **11.2c** the tunnel over Wi-Fi, with the 11.1 remote pairing: the `_remotepairing._tcp` port from its advert, pair-verify over TCP, encrypted messages (ChaCha20-Poly1305) and `createListener`, IPAForge's own TLS 1.2 PSK client (`TLS_PSK_WITH_AES_128_GCM_SHA256`, extended master secret: iOS refuses the SHA-1 suites Electron's BoringSSL has), then the same TCP client, RSD and services as over USB; an AFC upload through it measured at 9.3 MiB/s on iOS 26.6.1 (#99) + - [ ] **11.2d** installs through the Wi-Fi tunnel (a device session over it), connection states in the UI, recovery and docs - **11.3** Apple TV and Vision Pro as targets: found on the network, paired with the PIN on screen, installs through the 11.2 tunnel - not planned: Apple Watch as a target (Watch apps install with their iPhone app; installing to the Watch directly isn't documented) - [ ] **12. Release 1.0**: docs site, an upstream SideStore "preload manifest" proposal, translations, a security review (secrets, Electron hardening, CSP), a licence audit, and a tagged multi-platform release pipeline diff --git a/docs/device.md b/docs/device.md index 323b573b..592ab1de 100644 --- a/docs/device.md +++ b/docs/device.md @@ -49,6 +49,18 @@ From iOS 17.4 a device offers a second way to its services: a packet tunnel, the - **Services:** each lockdown service has a counterpart in the tunnel, `.shim.remote` (`com.apple.afc.shim.remote`, `com.apple.mobile.installation_proxy.shim.remote`, house_arrest, misagent, amfi). A connection to one starts with `RSDCheckin` (answered with `RSDCheckin`, then `StartService`) and then speaks the service's usual protocol without TLS, because the tunnel is already encrypted. AFC, installation_proxy and the rest run unchanged on top. A signed SideStore installed this way, tunnel only, in 2.1 s. - The tunnel closes with the session. +## The tunnel over Wi-Fi (iOS 17.4 and later) + +With the remote pairing made over USB ([Remote pairing](#remote-pairing-ios-174-and-later)), IPAForge can open the iOS 17+ CoreDevice tunnel to a device on Wi-Fi (`DeviceManager.openWifiTunnel`, the probe `rp-tunnel`). No Wi-Fi sync or admin rights are needed. + +1. **Find the remote pairing port:** the device's `_remotepairing._tcp` advert at its Wi-Fi address (port 49152 on the iPhones tested). +2. **Pair-verify** over that TCP connection with the saved identity. It gives a shared X25519 secret. +3. **An encrypted `createListener`** for a TCP tunnel. After pair-verify, messages are `streamEncrypted`: ChaCha20-Poly1305 under HKDF-SHA512 keys (`ClientEncrypt-main` from us, `ServerEncrypt-main` from the device), the nonce being each direction's message count as 8 little-endian bytes then 4 zero bytes. The device answers with the port of the tunnel. +4. **TLS 1.2 PSK** to that port, keyed with the pair-verify secret, empty identity. iOS refuses every SHA-1 and ECDHE-PSK cipher suite, which are all Electron's TLS library has, so IPAForge uses its own TLS 1.2 PSK client (`infrastructure/tls-psk`) with `TLS_PSK_WITH_AES_128_GCM_SHA256` and the extended master secret. It is tested against OpenSSL's server. +5. **The CDTunnel handshake** over the TLS connection, the same as over USB. It returns the device's address in the tunnel, ours with the netmask and MTU, and RemoteServiceDiscovery's port. The control connection stays open for the tunnel's life. + +Inside, the tunnel is the same as over USB: IPAForge's TCP client, RSD and the services (`DeviceTunnel`). The control connection closes with the tunnel. Measured on an iPhone on iOS 26.6.1: the tunnel and RSD in about 3.3 s, 73 services, an AFC upload of 20 MiB at 9.3 MiB/s with no retransmissions. The app's installs don't use it yet: they go through a device session, which runs over the Wi-Fi tunnel with 11.2d. + ## What it can do | Capability | Service | @@ -119,6 +131,7 @@ pnpm --filter @ipaforge/desktop device-probe pairing-status # clas pnpm --filter @ipaforge/desktop device-probe rp-pair # iOS 17.4+: makes a remote pairing, then verifies it (kept in memory only) pnpm --filter @ipaforge/desktop device-probe afc-speed [--mb 32] # times AFC writes per chunk size (written, then deleted) pnpm --filter @ipaforge/desktop device-probe wifi-list [--udid ] # finds known devices on Wi-Fi, without usbmuxd +pnpm --filter @ipaforge/desktop device-probe rp-tunnel [--udid ] # iOS 17.4+: opens the tunnel over Wi-Fi, prints what the device set up pnpm --filter @ipaforge/desktop device-probe info --direct [--udid ] # any device command, straight over Wi-Fi only pnpm --filter @ipaforge/desktop device-probe rsd-services # iOS 17.4+: the device's properties and services inside its tunnel pnpm --filter @ipaforge/desktop device-probe tunnel-install [] [--mb 100] [--compare] # a timed upload and install through the tunnel diff --git a/docs/roadmap.md b/docs/roadmap.md index cebb5ae3..81e61fa9 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -17,7 +17,7 @@ The detailed roadmap, with each phase's scope, is [design/roadmap.md](design/roa | 8 | Install & preload UX ✓ | One-click SideStore ✓, live run view ✓, recovery screens ✓, Apple ID switch ✓, preload picker ✓ (#59), app sources ✓ (#66), detailed install progress ✓ (#67), the Apps section ✓ (#68), Repair SideStore ✓ (#70), SideStore QR codes ✓ (#71), on-device checklist ✓ (#72), the smaller notes ✓ (#73), anisette servers in Settings ✓ (#80), days left as SideStore counts them and SideStore refreshed with its own date ✓ (#81), installs that never hang on a locked device and Cancel refresh ✓ (#93) | | 9 | Desktop app ✓ (#61, #62, #63, #64, #65, #69, #74, #75, #77) | Electron packages for Windows, macOS, Linux ✓; the macOS app signed with IPAForge's own certificate ✓; auto-update and What's new ✓ (#74); Windows signing and notarisation moved to 1.0 | | 10 | Management tools ✓ | Developer Portal page (#86), pairing files per app (#87), saving signed IPAs (#90), `.p12` import and export (#93) | -| 11 | Wireless & remote pairing | 11.1 the iOS 17.4+ remote pairing file for SideStore ✓ (#82); 11.2a Wi-Fi without usbmuxd, devices found on the network ✓ (#97); 11.2b the iOS 17.4+ device tunnel over USB ✓ (#98); 11.2c–d installing through it over Wi-Fi, connection states; 11.3 Apple TV and Vision Pro (installing over Wi-Fi to a paired device works already) | +| 11 | Wireless & remote pairing | 11.1 the iOS 17.4+ remote pairing file for SideStore ✓ (#82); 11.2a Wi-Fi without usbmuxd, devices found on the network ✓ (#97); 11.2b the iOS 17.4+ device tunnel over USB ✓ (#98); 11.2c the tunnel over Wi-Fi, with IPAForge's own TLS-PSK ✓ (#99); 11.2d installs through the Wi-Fi tunnel, connection states; 11.3 Apple TV and Vision Pro (installing over Wi-Fi to a paired device works already) | | 12 | Release 1.0 | Docs site, translations, security review, Windows code signing and Apple notarisation, reusable packages on npm | ## See Also diff --git a/packages/device/src/__tests__/fake-remote-device.ts b/packages/device/src/__tests__/fake-remote-device.ts index 8daa901e..4ec72fd1 100644 --- a/packages/device/src/__tests__/fake-remote-device.ts +++ b/packages/device/src/__tests__/fake-remote-device.ts @@ -1,6 +1,8 @@ // The device side of remote pairing, for tests: an SRP server with the USB PIN, its own Ed25519 identity, and the // replies to pair-setup (M2, M4, M6) and pair-verify (M2, M4), as a PairingChannel the host code talks to. +import { chacha20poly1305 } from '@noble/ciphers/chacha.js' import { ed25519, x25519 } from '@noble/curves/ed25519.js' +import { hkdf } from '@noble/hashes/hkdf.js' import { sha512 } from '@noble/hashes/sha2.js' import { @@ -48,6 +50,8 @@ const random = (length: number) => globalThis.crypto.getRandomValues(new Uint8Array(length)) export type FakeRemoteDeviceOptions = { + /** The port createListener answers with (a network connection's tunnel). */ + readonly listenerPort?: number /** The device asks the user first (sends awaitingUserConsent before M2). */ readonly asksConsent?: boolean /** The device refuses outright, with this reason. */ @@ -83,6 +87,11 @@ export const createFakeRemoteDevice = ( key: Uint8Array } | undefined + /** The pair-verify secret, keying the encrypted messages that follow it. */ + let shared: Uint8Array | undefined + const encrypted: Record[] = [] + let fromHost = 0 + let toHost = 0 const errorRecord = () => pairingData([[TlvType.Error, new Uint8Array([2])]]) const setupStep = (tlv: ReadonlyMap) => { @@ -230,6 +239,7 @@ export const createFakeRemoteDevice = ( KeyDerivation.verifyEncrypt ) verify = { secret, publicKey, hostKey, key } + shared = x25519.getSharedSecret(secret, hostKey) const id = utf8Encode(DEVICE_ID) queue.push( pairingData([ @@ -305,8 +315,77 @@ export const createFakeRemoteDevice = ( if (!next) throw new Error('the fake device has nothing to say') return next }, + sendMessage: async (message) => { + const plain = valueAt(message, ['plain', '_0']) + if (plain && typeof plain === 'object') + return channel.send(plain as Record) + const sealed = valueAt(message, ['streamEncrypted', '_0']) + if (typeof sealed !== 'string' || !shared) + throw new Error('the fake device got a message it cannot read') + const key = (info: string) => + hkdf( + sha512, + shared ?? new Uint8Array(), + new Uint8Array(0), + utf8Encode(info), + 32 + ) + const nonce = (counter: number) => { + const bytes = new Uint8Array(12) + new DataView(bytes.buffer).setBigUint64(0, BigInt(counter), true) + return bytes + } + const body = JSON.parse( + utf8Decode( + chacha20poly1305( + key('ClientEncrypt-main'), + nonce(fromHost++) + ).decrypt(fromBase64(sealed)) + ) + ) as Record + encrypted.push(body) + const reply = valueAt(body, ['request', '_0', 'createListener']) + ? { + response: { + _1: { + createListener: { + port: options.listenerPort ?? 50_000, + serviceName: 'FAKE-SERVICE', + devicePublicKey: 'FAKE' + } + } + } + } + : { + response: { + _1: { errorExtended: { _0: { reason: 'unknown request' } } } + } + } + queue.push({ + streamEncrypted: { + _0: toBase64( + chacha20poly1305( + key('ServerEncrypt-main'), + nonce(toHost++) + ).encrypt(utf8Encode(JSON.stringify(reply))) + ) + } + }) + }, + receiveMessage: async () => { + const next = queue.shift() + if (!next) throw new Error('the fake device has nothing to say') + return next.streamEncrypted ? next : { plain: { _0: next } } + }, close: async () => {} } - return { channel, sent, devicePublicKey, known } + return { + channel, + sent, + encrypted, + devicePublicKey, + known, + shared: () => shared + } } diff --git a/packages/device/src/__tests__/mdns-answer.ts b/packages/device/src/__tests__/mdns-answer.ts index 866bf50e..b6920252 100644 --- a/packages/device/src/__tests__/mdns-answer.ts +++ b/packages/device/src/__tests__/mdns-answer.ts @@ -69,6 +69,8 @@ export const aData = (address: string) => new Uint8Array(address.split('.').map(Number)) export type FakeAdvert = { + /** The service advertised: lockdown over Wi-Fi unless said otherwise. */ + readonly service?: string readonly mac: string readonly host: string readonly address: string @@ -78,10 +80,17 @@ export type FakeAdvert = { /** A device's whole advert in one answer, as iOS sends it: PTR, SRV, TXT and A. */ export const lockdownAdvert = ( - { mac, host, address, txt = [], ttl }: FakeAdvert, + { + service = WIFI_LOCKDOWN_SERVICE, + mac, + host, + address, + txt = [], + ttl + }: FakeAdvert, id = 0 ) => { - const instance = `${mac}@fe80::1-supportsRP-24.${WIFI_LOCKDOWN_SERVICE}` + const instance = `${mac}@fe80::1-supportsRP-24.${service}` const at = (record: Omit) => ({ ...record, ...(ttl === undefined ? {} : { ttl }) @@ -90,7 +99,7 @@ export const lockdownAdvert = ( return mdnsMessage( [ at({ - name: WIFI_LOCKDOWN_SERVICE, + name: service, type: RecordType.PTR, data: ptrData(instance) }), diff --git a/packages/device/src/application/manager.ts b/packages/device/src/application/manager.ts index e7263c11..f51b5694 100644 --- a/packages/device/src/application/manager.ts +++ b/packages/device/src/application/manager.ts @@ -21,9 +21,11 @@ import { } from '@device/application/pair-records.ts' import { openSession } from '@device/application/session.ts' import type { + DeviceTunnel, OpenSessionOptions, PairOptions } from '@device/application/types.ts' +import { openWifiTunnel } from '@device/application/wifi-tunnel.ts' import { resolveDeviceDeps } from '@device/deps.ts' import { shortUdid } from '@device/domain/device.ts' import type { PairRecord } from '@device/domain/pairing/types.ts' @@ -49,6 +51,11 @@ export type DeviceManager = { ): Promise /** Searches the network for a few seconds and returns the known devices found there. */ discoverNetwork(): Promise + /** + * Opens the iOS 17.4+ tunnel to `udid` on Wi-Fi, with its saved remote pairing (make one over USB first, + * `DeviceHandle.remotePairing`). Close it when done. + */ + openWifiTunnel(udid: string): Promise pair(udid: string, options?: PairOptions): Promise isPaired(udid: string): Promise exportPairRecord(udid: string): Promise @@ -133,6 +140,8 @@ export const createDeviceManager = (input: DeviceDepsInput): DeviceManager => { watchNetwork: (onEvent, signal) => watchNetworkDevices(ctx, onEvent, signal), discoverNetwork: () => discoverNetworkDevices(ctx), + openWifiTunnel: async (udid) => + openWifiTunnel(ctx, await findOnWifi(ctx, udid)), pair: async (udid, options) => (await pairDevice(ctx, await findDevice(ctx, udid), options)).record, isPaired: async (udid) => (await getPairRecord(ctx, udid)) !== undefined, diff --git a/packages/device/src/application/remote-pairing.ts b/packages/device/src/application/remote-pairing.ts index 34d6f4cf..6dfae0f9 100644 --- a/packages/device/src/application/remote-pairing.ts +++ b/packages/device/src/application/remote-pairing.ts @@ -63,7 +63,8 @@ const newHostIdentity = (): HostIdentity => { } } -const hostNameOf = (identifier: string): string => +/** How this computer is named on the device for a pairing: the same for the pairing's life. */ +export const hostNameOf = (identifier: string): string => `${HOST_NAME_PREFIX}-${identifier.slice(0, 6).toLowerCase()}` const withChannel = async ( @@ -78,7 +79,8 @@ const withChannel = async ( const isRefusal = (error: unknown): boolean => error instanceof IPAForgeError && error.code === ErrorCode.PairingDenied -const savedRecord = async (ctx: DeviceContext, udid: string) => +/** The remote pairing saved for `udid`, when one was made. */ +export const savedRecord = async (ctx: DeviceContext, udid: string) => parseRemotePairing(await ctx.deps.secrets.get(remotePairingSecretKey(udid))) const verify = (session: DeviceSession, record: RemotePairingRecord) => diff --git a/packages/device/src/application/tunnel.ts b/packages/device/src/application/tunnel.ts index 0836cddd..6853f41f 100644 --- a/packages/device/src/application/tunnel.ts +++ b/packages/device/src/application/tunnel.ts @@ -1,5 +1,6 @@ -// Opening the iOS 17.4+ device tunnel over a session's link: CoreDeviceProxy, the CDTunnel handshake, our own TCP -// over its packets, then RSD for the service map. Addresses, ports and the MTU are fresh for every tunnel. +// Opening the iOS 17.4+ device tunnel: over a session's link (CoreDeviceProxy) or over Wi-Fi (the remote pairing +// listener's TLS-PSK, wifi-tunnel.ts), then the CDTunnel handshake, our own TCP over its packets, and RSD for the +// service map. Addresses, ports and the MTU are fresh for every tunnel. import type { DeviceContext } from '@device/application/context.ts' import type { DeviceTunnel } from '@device/application/types.ts' import { CORE_DEVICE_PROXY_SERVICE } from '@device/domain/constants.ts' @@ -86,10 +87,22 @@ export const openDeviceTunnel = async ( ctx: DeviceContext, device: UsbmuxDevice, startService: (service: string) => Promise +): Promise => + openTunnelOver(ctx, device, await startProxy(device, startService)) + +/** + * The tunnel over a connection that carries it (CoreDeviceProxy's over USB, the remote pairing listener's TLS over + * Wi-Fi): the CDTunnel handshake, our own TCP over its packets, then RSD. `onClose` closes what the carrier + * depends on (the remote pairing control connection over Wi-Fi), after the tunnel. + */ +export const openTunnelOver = async ( + ctx: DeviceContext, + device: UsbmuxDevice, + proxy: Link, + onClose: () => Promise = async () => {} ): Promise => { const { logger, config } = ctx.deps const started = ctx.deps.clock.now().getTime() - const proxy = await startProxy(device, startService) const parameters = await closeOnError(proxy, (link) => cdTunnelHandshake(link, config.tunnelMtu) ) @@ -137,6 +150,7 @@ export const openDeviceTunnel = async ( stats: () => ({ ...stack.stats }), close: async () => { await stack.close() + await onClose() logger.debug('tunnel closed', { device: shortUdid(device.udid) }) } } diff --git a/packages/device/src/application/wifi-tunnel.ts b/packages/device/src/application/wifi-tunnel.ts new file mode 100644 index 00000000..e464e612 --- /dev/null +++ b/packages/device/src/application/wifi-tunnel.ts @@ -0,0 +1,162 @@ +// The iOS 17.4+ tunnel over Wi-Fi, with the remote pairing made over USB (11.1): TCP to the device's remote pairing +// port (`_remotepairing._tcp`), pair-verify, an encrypted `createListener` for a TCP tunnel, IPAForge's own TLS 1.2 +// PSK to the port it gives (keyed with the pair-verify secret). Over that, the same tunnel as over USB: the CDTunnel +// handshake, our TCP client, RSD and the services. The steps were checked against iPhones on iOS 18.2 and 26.6.1. +import { z } from 'zod' + +import type { DeviceContext } from '@device/application/context.ts' +import { hostNameOf, savedRecord } from '@device/application/remote-pairing.ts' +import { openTunnelOver } from '@device/application/tunnel.ts' +import type { DeviceTunnel } from '@device/application/types.ts' +import { shortUdid } from '@device/domain/device.ts' +import type { Connection } from '@device/domain/ports/types.ts' +import type { UsbmuxDevice } from '@device/domain/types.ts' +import { closeOnError } from '@device/infrastructure/closeable.ts' +import { createLink } from '@device/infrastructure/framing/link.ts' +import { browseService } from '@device/infrastructure/mdns/browser.ts' +import { REMOTE_PAIRING_SERVICE } from '@device/infrastructure/mdns/constants.ts' +import { createPairingChannel } from '@device/infrastructure/remote-pairing/channel.ts' +import { createEncryptedChannel } from '@device/infrastructure/remote-pairing/encrypted-channel.ts' +import { pairVerify } from '@device/infrastructure/remote-pairing/pair-verify.ts' +import { connectTlsPsk } from '@device/infrastructure/tls-psk/connection.ts' +import { ErrorCode, IPAForgeError, toBase64 } from '@ipaforge/kernel' + +const listenerSchema = z.object({ + response: z.object({ + _1: z.object({ + createListener: z.object({ port: z.number().int().positive() }) + }) + }) +}) + +const randomBytes = (length: number): Uint8Array => + globalThis.crypto.getRandomValues(new Uint8Array(length)) + +const unreachable = (udid: string, message: string) => + new IPAForgeError(ErrorCode.DeviceNotFound, { + message, + data: { device: shortUdid(udid) } + }) + +/** The port the device's remote pairing listens on, from its advert at `address`. */ +const remotePairingPort = async ( + ctx: DeviceContext, + device: UsbmuxDevice, + address: string +): Promise => { + const { transport, sleep, clock, logger, config } = ctx.deps + if (!transport.openMulticast) + throw unreachable(device.udid, 'this host cannot search the network') + const socket = await transport.openMulticast() + const controller = new AbortController() + let port: number | undefined + try { + const search = browseService( + socket, + REMOTE_PAIRING_SERVICE, + { + sleep, + now: () => clock.now().getTime(), + intervalMs: config.networkBrowseMs, + logger + }, + (event) => { + if (event.kind !== 'found' || event.advert.address !== address) return + port = event.advert.port + controller.abort() + }, + controller.signal + ) + await Promise.race([ + search, + sleep(config.networkBrowseMs).then(() => controller.abort()) + ]) + await search + } finally { + await socket.close() + } + if (port === undefined) + throw unreachable( + device.udid, + 'its remote pairing was not found on the network' + ) + return port +} + +const connectTo = ( + ctx: DeviceContext, + address: string, + port: number +): Promise => { + const { connectTcp } = ctx.deps.transport + if (!connectTcp) + throw new IPAForgeError(ErrorCode.DeviceNotFound, { + message: 'this host cannot connect to devices on the network' + }) + return connectTcp(address, port) +} + +const createListenerRequest = (secret: Uint8Array) => ({ + request: { + _0: { + createListener: { + key: toBase64(secret), + peerConnectionsInfo: [ + { owningPID: 0, owningProcessName: 'CoreDeviceService' } + ], + transportProtocolType: 'tcp' + } + } + } +}) + +/** Opens the tunnel to a device on Wi-Fi with its saved remote pairing; close it when done. */ +export const openWifiTunnel = async ( + ctx: DeviceContext, + device: UsbmuxDevice +): Promise => { + const { address } = device + if (address === undefined) + throw unreachable(device.udid, 'the device is not on Wi-Fi') + const record = await savedRecord(ctx, device.udid) + if (!record) + throw new IPAForgeError(ErrorCode.DeviceNotPaired, { + message: 'no remote pairing yet: make one over USB first', + data: { device: shortUdid(device.udid) } + }) + const port = await remotePairingPort(ctx, device, address) + // The control connection stays open for the tunnel's life: the device ends the tunnel when it closes. + const control = createLink(await connectTo(ctx, address, port)) + + return closeOnError(control, async () => { + const channel = createPairingChannel(control) + const secret = await pairVerify(channel, { + record, + hostName: hostNameOf(record.identifier), + randomBytes + }) + const reply = await createEncryptedChannel(channel, secret).request( + createListenerRequest(secret) + ) + const listener = listenerSchema.safeParse(reply) + if (!listener.success) + throw new IPAForgeError(ErrorCode.DeviceProtocolError, { + message: 'remote pairing: the device did not open a tunnel listener' + }) + const raw = await connectTo( + ctx, + address, + listener.data.response._1.createListener.port + ) + const link = createLink( + await closeOnError(raw, (connection) => + connectTlsPsk(connection, { psk: secret, randomBytes }) + ) + ) + ctx.deps.logger.info('tunnel carrier open over Wi-Fi', { + device: shortUdid(device.udid) + }) + + return openTunnelOver(ctx, device, link, () => control.close()) + }) +} diff --git a/packages/device/src/application/wifi.test.ts b/packages/device/src/application/wifi.test.ts index 89df94de..23436236 100644 --- a/packages/device/src/application/wifi.test.ts +++ b/packages/device/src/application/wifi.test.ts @@ -21,6 +21,15 @@ import { utf8Encode } from '@ipaforge/kernel' +const codeOf = async (promise: Promise) => { + try { + await promise + } catch (error) { + return (error as { code?: string }).code + } + return undefined +} + const WIFI_KEY = `${LockdownDomain.WirelessLockdown}/${WIFI_CONNECTIONS_KEY}` const ADDRESS = '192.0.2.10' @@ -181,4 +190,17 @@ describe('Wi-Fi without usbmuxd', () => { expect(await rig.manager.discoverNetwork()).toEqual([]) }) + + it('opens no tunnel to a device that is not on Wi-Fi, or has no remote pairing yet', async () => { + const rig = await createRig() + await openAndClose(rig) + expect(await codeOf(rig.manager.openWifiTunnel(rig.device.udid))).toBe( + ErrorCode.DeviceNotFound + ) + + moveToWifi(rig) + expect(await codeOf(rig.manager.openWifiTunnel(rig.device.udid))).toBe( + ErrorCode.DeviceNotPaired + ) + }) }) diff --git a/packages/device/src/index.ts b/packages/device/src/index.ts index c28be78c..972ca6d4 100644 --- a/packages/device/src/index.ts +++ b/packages/device/src/index.ts @@ -95,6 +95,7 @@ export { serializeKnownDevices, WIFI_DEVICES_KEY } from '@device/domain/wifi.ts' +export { createAfcClient } from '@device/infrastructure/afc/client.ts' export type { AfcClient, AfcStat } from '@device/infrastructure/afc/types.ts' export type { ContainerMode } from '@device/infrastructure/house-arrest/client.ts' export type { InstalledApp } from '@device/infrastructure/installation-proxy/apps.ts' @@ -114,5 +115,9 @@ export type { XpcValue } from '@device/infrastructure/rsd/types.ts' export { XpcUuid } from '@device/infrastructure/rsd/xpc-uuid.ts' +export { + connectTlsPsk, + type TlsPskOptions +} from '@device/infrastructure/tls-psk/connection.ts' export type { TcpStats } from '@device/infrastructure/tunnel/types.ts' export type { DeviceDeps, DeviceDepsInput, Sleep } from '@device/types.ts' diff --git a/packages/device/src/infrastructure/mdns/browser.ts b/packages/device/src/infrastructure/mdns/browser.ts index df8b4fde..b4d0c4f7 100644 --- a/packages/device/src/infrastructure/mdns/browser.ts +++ b/packages/device/src/infrastructure/mdns/browser.ts @@ -30,11 +30,22 @@ const txtValues = (entries: readonly string[], key: string): string[] => const sameAdvert = (a: WifiAdvert, b: WifiAdvert): boolean => a.address === b.address && + a.port === b.port && a.identifier === b.identifier && a.authTags.join() === b.authTags.join() -export const browseWifiDevices = async ( +export const browseWifiDevices = ( socket: MulticastSocket, + options: BrowseOptions, + onEvent: (event: BrowseEvent) => void, + signal: AbortSignal +): Promise => + browseService(socket, WIFI_LOCKDOWN_SERVICE, options, onEvent, signal) + +/** The same search for any DNS-SD service type (`_remotepairing._tcp.local` for the remote pairing tunnel). */ +export const browseService = async ( + socket: MulticastSocket, + service: string, { sleep, now, intervalMs, logger }: BrowseOptions, onEvent: (event: BrowseEvent) => void, signal: AbortSignal @@ -70,6 +81,7 @@ export const browseWifiDevices = async ( const advert: WifiAdvert = { instance, address, + port: partial.port, mac: macOfInstance(instance), identifier: partial.identifier, authTags: partial.authTags @@ -82,10 +94,7 @@ export const browseWifiDevices = async ( } const take = (record: ResourceRecord) => { - if ( - record.type === RecordType.PTR && - record.name === WIFI_LOCKDOWN_SERVICE - ) { + if (record.type === RecordType.PTR && record.name === service) { if (record.ttl === 0) lose(record.target) else if (!partials.has(record.target)) partials.set(record.target, { authTags: [] }) @@ -97,7 +106,10 @@ export const browseWifiDevices = async ( } const partial = partials.get(record.name) if (!partial) return - if (record.type === RecordType.SRV) partial.host = record.target + if (record.type === RecordType.SRV) { + partial.host = record.target + partial.port = record.port + } if (record.type === RecordType.TXT) { partial.identifier = txtValues(record.entries, 'identifier')[0] partial.authTags = txtValues(record.entries, 'authTag') @@ -129,7 +141,7 @@ export const browseWifiDevices = async ( const stop = socket.onMessage(({ bytes }) => onMessage(bytes)) try { while (!signal.aborted) { - await send([{ name: WIFI_LOCKDOWN_SERVICE, type: RecordType.PTR }]) + await send([{ name: service, type: RecordType.PTR }]) try { await sleep(intervalMs, signal) } catch { diff --git a/packages/device/src/infrastructure/mdns/constants.ts b/packages/device/src/infrastructure/mdns/constants.ts index bddfd853..571d1ce1 100644 --- a/packages/device/src/infrastructure/mdns/constants.ts +++ b/packages/device/src/infrastructure/mdns/constants.ts @@ -19,5 +19,8 @@ export const CLASS_MASK = 0x7f_ff /** The service a device advertises while it takes lockdown connections over Wi-Fi. */ export const WIFI_LOCKDOWN_SERVICE = '_apple-mobdev2._tcp.local' +/** The service an iOS 17+ device's remote pairing listens on: the way to its tunnel over Wi-Fi. */ +export const REMOTE_PAIRING_SERVICE = '_remotepairing._tcp.local' + /** Most compression pointers a name may follow before it counts as a loop. */ export const MAX_NAME_JUMPS = 32 diff --git a/packages/device/src/infrastructure/mdns/mdns.test.ts b/packages/device/src/infrastructure/mdns/mdns.test.ts index fb5e457c..faae3835 100644 --- a/packages/device/src/infrastructure/mdns/mdns.test.ts +++ b/packages/device/src/infrastructure/mdns/mdns.test.ts @@ -3,8 +3,12 @@ import { describe, expect, it } from 'vitest' import { lockdownAdvert, ptrData } from '@device/__tests__/mdns-answer.ts' import type { Datagram, MulticastSocket } from '@device/domain/ports/types.ts' import { authTagMatches } from '@device/infrastructure/mdns/auth-tag.ts' -import { browseWifiDevices } from '@device/infrastructure/mdns/browser.ts' import { + browseService, + browseWifiDevices +} from '@device/infrastructure/mdns/browser.ts' +import { + REMOTE_PAIRING_SERVICE, RecordType, WIFI_LOCKDOWN_SERVICE } from '@device/infrastructure/mdns/constants.ts' @@ -164,7 +168,7 @@ const browse = async ( } describe('searching the network', () => { - it('finds a device once, with its address, MAC and TXT values', async () => { + it('finds a device once, with its address, port, MAC and TXT values', async () => { const { socket, sent } = fakeSocket(() => [lockdownAdvert(ADVERT)]) const events = await browse(socket, 2) expect(events).toEqual([ @@ -173,6 +177,7 @@ describe('searching the network', () => { advert: { instance: `${ADVERT.mac}@fe80::1-supportsRP-24.${WIFI_LOCKDOWN_SERVICE}`, address: '192.0.2.10', + port: 32498, mac: ADVERT.mac, identifier: '0A1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D', authTags: ['dr5/vaK9kIw='] @@ -198,6 +203,39 @@ describe('searching the network', () => { expect(quiet.map((event) => event.kind)).toEqual(['found', 'lost']) }) + it("searches for any service: a device's remote pairing advert, with its port", async () => { + const { socket } = fakeSocket(() => [ + lockdownAdvert({ ...ADVERT, service: REMOTE_PAIRING_SERVICE }), + lockdownAdvert(ADVERT) + ]) + const events: BrowseEvent[] = [] + const controller = new AbortController() + await browseService( + socket, + REMOTE_PAIRING_SERVICE, + { + logger: silentLogger, + intervalMs: 1000, + now: () => 0, + sleep: async () => controller.abort() + }, + (event) => events.push(event), + controller.signal + ) + + // Only the service asked for: the lockdown advert in the same answer is not this search's. + expect(events).toEqual([ + { + kind: 'found', + advert: expect.objectContaining({ + instance: expect.stringContaining(REMOTE_PAIRING_SERVICE), + address: '192.0.2.10', + port: 32498 + }) + } + ]) + }) + it('stops with local_network_denied when the OS refuses the search', async () => { const { socket } = fakeSocket(() => [], true) await expect(browse(socket, 1)).rejects.toMatchObject({ diff --git a/packages/device/src/infrastructure/mdns/types.ts b/packages/device/src/infrastructure/mdns/types.ts index 6fdbf268..d97ea4ce 100644 --- a/packages/device/src/infrastructure/mdns/types.ts +++ b/packages/device/src/infrastructure/mdns/types.ts @@ -49,6 +49,8 @@ export type WifiAdvert = { readonly instance: string /** Its IPv4 address. */ readonly address: string + /** The service's port (SRV), when the answer gave it. */ + readonly port?: number | undefined /** The MAC address in the instance name: the device's real one, or a private one for this network. */ readonly mac?: string | undefined /** TXT `identifier` and `authTag` values (iOS 26.4 and later), checked against the pair records. */ @@ -71,6 +73,7 @@ export type BrowseOptions = { /** What one search knows of an instance before its address is in: where it is, and its TXT values. */ export type PendingAdvert = { host?: string + port?: number identifier?: string | undefined authTags: string[] } diff --git a/packages/device/src/infrastructure/remote-pairing/channel.ts b/packages/device/src/infrastructure/remote-pairing/channel.ts index c035a86b..5e824119 100644 --- a/packages/device/src/infrastructure/remote-pairing/channel.ts +++ b/packages/device/src/infrastructure/remote-pairing/channel.ts @@ -22,6 +22,10 @@ export type PairingChannel = { send(body: Record): Promise /** The next body the device sent. */ receive(): Promise> + /** Sends an envelope with this `message` (plain or encrypted), with the next sequence number. */ + sendMessage(message: Record): Promise + /** The next envelope's `message`, whatever it holds. */ + receiveMessage(): Promise> close(): Promise } @@ -56,30 +60,35 @@ export const bodyOf = (envelope: unknown): Record => { export const createPairingChannel = (link: Link): PairingChannel => { let sequenceNumber = 0 + const sendMessage = async (message: Record) => { + const envelope = { message, originatedBy: 'host', sequenceNumber } + sequenceNumber += 1 + await link.write(encodeFrame(envelope)) + } + + const receiveEnvelope = async (): Promise => { + const magic = await link.reader.readExact(MAGIC.byteLength) + if (!magic.every((byte, index) => byte === MAGIC[index])) + throw malformed('a frame without the RPPairing tag') + const header = await link.reader.readExact(LENGTH_BYTES) + const length = new DataView(header.buffer, header.byteOffset).getUint16(0) + const json = utf8Decode(await link.reader.readExact(length)) + try { + return JSON.parse(json) + } catch { + throw malformed('a frame that is not JSON') + } + } + return { - send: async (body) => { - const envelope = { - message: { plain: { _0: body } }, - originatedBy: 'host', - sequenceNumber - } - sequenceNumber += 1 - await link.write(encodeFrame(envelope)) - }, - receive: async () => { - const magic = await link.reader.readExact(MAGIC.byteLength) - if (!magic.every((byte, index) => byte === MAGIC[index])) - throw malformed('a frame without the RPPairing tag') - const header = await link.reader.readExact(LENGTH_BYTES) - const length = new DataView(header.buffer, header.byteOffset).getUint16(0) - const json = utf8Decode(await link.reader.readExact(length)) - let envelope: unknown - try { - envelope = JSON.parse(json) - } catch { - throw malformed('a frame that is not JSON') - } - return bodyOf(envelope) + send: (body) => sendMessage({ plain: { _0: body } }), + receive: async () => bodyOf(await receiveEnvelope()), + sendMessage, + receiveMessage: async () => { + const envelope = await receiveEnvelope() + const message = isRecord(envelope) ? envelope.message : undefined + if (!isRecord(message)) throw malformed('an envelope without a message') + return message }, close: () => link.close() } diff --git a/packages/device/src/infrastructure/remote-pairing/encrypted-channel.ts b/packages/device/src/infrastructure/remote-pairing/encrypted-channel.ts new file mode 100644 index 00000000..b450edd0 --- /dev/null +++ b/packages/device/src/infrastructure/remote-pairing/encrypted-channel.ts @@ -0,0 +1,86 @@ +// After pair-verify on a network connection, remote pairing's messages are encrypted: each JSON body sealed with +// ChaCha20-Poly1305 under a key per direction (HKDF-SHA512 of the pair-verify secret, no salt, info +// `ClientEncrypt-main` / `ServerEncrypt-main`), the nonce being each direction's message count as 8 little-endian +// bytes then 4 zero bytes, sent base64 as `streamEncrypted._0`. Checked against iPhones on iOS 18.2 and 26.6.1. +import { chacha20poly1305 } from '@noble/ciphers/chacha.js' +import { hkdf } from '@noble/hashes/hkdf.js' +import { sha512 } from '@noble/hashes/sha2.js' + +import { isRecord } from '@device/domain/remote-pairing/json.ts' +import type { PairingChannel } from '@device/infrastructure/remote-pairing/channel.ts' +import { + ErrorCode, + fromBase64, + IPAForgeError, + toBase64, + utf8Decode, + utf8Encode +} from '@ipaforge/kernel' + +const KEY_BYTES = 32 +const NONCE_BYTES = 12 +const CLIENT_KEY_INFO = 'ClientEncrypt-main' +const SERVER_KEY_INFO = 'ServerEncrypt-main' +/** Plain events (such as consent prompts) the device may send before its encrypted answer. */ +const MAX_SKIPPED_MESSAGES = 16 + +export type EncryptedChannel = { + /** Sends `body` encrypted and returns the device's next encrypted body, opened. */ + request(body: Record): Promise> +} + +const keyFor = (secret: Uint8Array, info: string) => + hkdf(sha512, secret, new Uint8Array(0), utf8Encode(info), KEY_BYTES) + +const nonceFor = (counter: number): Uint8Array => { + const nonce = new Uint8Array(NONCE_BYTES) + new DataView(nonce.buffer).setBigUint64(0, BigInt(counter), true) + return nonce +} + +const malformed = (message: string) => + new IPAForgeError(ErrorCode.DeviceProtocolError, { + message: `remote pairing: ${message}` + }) + +export const createEncryptedChannel = ( + channel: PairingChannel, + secret: Uint8Array +): EncryptedChannel => { + const sendKey = keyFor(secret, CLIENT_KEY_INFO) + const receiveKey = keyFor(secret, SERVER_KEY_INFO) + let sent = 0 + let received = 0 + + const open = (sealed: string): Record => { + let body: unknown + try { + const plain = chacha20poly1305(receiveKey, nonceFor(received)).decrypt( + fromBase64(sealed) + ) + body = JSON.parse(utf8Decode(plain)) + } catch { + throw malformed("an encrypted message that doesn't open") + } + received += 1 + if (!isRecord(body)) throw malformed('an encrypted message without a body') + return body + } + + return { + request: async (body) => { + const sealed = chacha20poly1305(sendKey, nonceFor(sent)).encrypt( + utf8Encode(JSON.stringify(body)) + ) + sent += 1 + await channel.sendMessage({ streamEncrypted: { _0: toBase64(sealed) } }) + for (let skipped = 0; skipped < MAX_SKIPPED_MESSAGES; skipped++) { + const message = await channel.receiveMessage() + const encrypted = message.streamEncrypted + if (isRecord(encrypted) && typeof encrypted._0 === 'string') + return open(encrypted._0) + } + throw malformed('no encrypted answer') + } + } +} diff --git a/packages/device/src/infrastructure/remote-pairing/pair-verify.ts b/packages/device/src/infrastructure/remote-pairing/pair-verify.ts index 9b9f19e7..dfdb3ce6 100644 --- a/packages/device/src/infrastructure/remote-pairing/pair-verify.ts +++ b/packages/device/src/infrastructure/remote-pairing/pair-verify.ts @@ -1,6 +1,7 @@ // Pair-verify: whether the device still accepts a remote pairing. A fresh X25519 exchange, the device proving it is // the device pair-setup met (its Ed25519 signature over both ephemeral keys), then this computer proving the same. -// The device answers M3 with an error record when it no longer knows this computer. +// The device answers M3 with an error record when it no longer knows this computer. Returns the X25519 shared +// secret: on a network connection it keys what follows (the encrypted messages, the tunnel's TLS-PSK). import { ed25519, x25519 } from '@noble/curves/ed25519.js' import { @@ -47,7 +48,7 @@ const notAccepted = (message: string) => export const pairVerify = async ( channel: PairingChannel, { record, hostName, randomBytes }: PairVerifyOptions -): Promise => { +): Promise => { const step = (data: Uint8Array, startNewSession = false) => exchange(channel, { data, @@ -67,10 +68,8 @@ export const pairVerify = async ( true ) const deviceKey = requireTlv(m2, TlvType.PublicKey, 'verify key') - const encryptKey = deriveKey( - x25519.getSharedSecret(secret, deviceKey), - KeyDerivation.verifyEncrypt - ) + const sharedSecret = x25519.getSharedSecret(secret, deviceKey) + const encryptKey = deriveKey(sharedSecret, KeyDerivation.verifyEncrypt) let device: ReturnType try { device = decodeTlv8( @@ -124,4 +123,6 @@ export const pairVerify = async ( ] ]) ) + + return sharedSecret } diff --git a/packages/device/src/infrastructure/remote-pairing/remote-pairing.test.ts b/packages/device/src/infrastructure/remote-pairing/remote-pairing.test.ts index a3fa37cc..27626f88 100644 --- a/packages/device/src/infrastructure/remote-pairing/remote-pairing.test.ts +++ b/packages/device/src/infrastructure/remote-pairing/remote-pairing.test.ts @@ -19,6 +19,7 @@ import { createPairingChannel, encodeFrame } from '@device/infrastructure/remote-pairing/channel.ts' +import { createEncryptedChannel } from '@device/infrastructure/remote-pairing/encrypted-channel.ts' import { pairSetup } from '@device/infrastructure/remote-pairing/pair-setup.ts' import { pairVerify } from '@device/infrastructure/remote-pairing/pair-verify.ts' import { ErrorCode, utf8Decode } from '@ipaforge/kernel' @@ -101,16 +102,45 @@ describe('remote pair-setup', () => { }) describe('remote pair-verify', () => { - it('is accepted by the device that pairing was made with', async () => { + it('is accepted by the device that pairing was made with, sharing its secret', async () => { const device = createFakeRemoteDevice() const record = await pairSetup(device.channel, { host: hostIdentity(), randomBytes }) - await expect( - pairVerify(device.channel, { record, hostName: 'IPAForge', randomBytes }) - ).resolves.toBeUndefined() + const secret = await pairVerify(device.channel, { + record, + hostName: 'IPAForge', + randomBytes + }) + expect(secret).toEqual(device.shared()) + }) + + it('then sends requests encrypted, and opens the encrypted answer', async () => { + const device = createFakeRemoteDevice({ listenerPort: 51_234 }) + const record = await pairSetup(device.channel, { + host: hostIdentity(), + randomBytes + }) + const secret = await pairVerify(device.channel, { + record, + hostName: 'IPAForge', + randomBytes + }) + const encrypted = createEncryptedChannel(device.channel, secret) + + const first = await encrypted.request({ + request: { _0: { createListener: {} } } + }) + const second = await encrypted.request({ + request: { _0: { createListener: {} } } + }) + expect(first).toMatchObject({ + response: { _1: { createListener: { port: 51_234 } } } + }) + expect(second).toEqual(first) + expect(device.encrypted).toHaveLength(2) }) it('is refused once the device forgot this computer', async () => { diff --git a/packages/device/src/infrastructure/tls-psk/connection.ts b/packages/device/src/infrastructure/tls-psk/connection.ts new file mode 100644 index 00000000..ffe08e9d --- /dev/null +++ b/packages/device/src/infrastructure/tls-psk/connection.ts @@ -0,0 +1,85 @@ +// A TLS 1.2 PSK connection over another `Connection`, as a `Connection` itself: what the remote pairing tunnel runs +// on. iOS refuses the PSK cipher suites of Electron's TLS library (the SHA-1 ones), so this is IPAForge's own, +// with the one suite iOS takes: TLS_PSK_WITH_AES_128_GCM_SHA256. +import type { Connection } from '@device/domain/ports/types.ts' +import { + AlertDescription, + ContentType, + MAX_FRAGMENT_BYTES +} from '@device/infrastructure/tls-psk/constants.ts' +import { handshake } from '@device/infrastructure/tls-psk/handshake.ts' +import { + createRecordReader, + openRecord, + sealRecord, + tlsError +} from '@device/infrastructure/tls-psk/records.ts' + +export type TlsPskOptions = { + readonly psk: Uint8Array + readonly randomBytes: (length: number) => Uint8Array +} + +/** Runs the handshake over `connection` and returns the protected connection; throws when the server refuses. */ +export const connectTlsPsk = async ( + connection: Connection, + { psk, randomBytes }: TlsPskOptions +): Promise => { + const readRecord = createRecordReader(connection) + const keys = await handshake( + { readRecord, write: (bytes) => connection.write(bytes), randomBytes }, + psk + ) + let isClosed = false + + return { + read: async () => { + for (;;) { + const record = await readRecord() + if (!record) return null + const plain = openRecord(keys.receive, record) + if (record.type === ContentType.ApplicationData) { + if (plain.length > 0) return plain + continue + } + if (record.type === ContentType.Alert) { + if (plain[1] === AlertDescription.CloseNotify) return null + throw tlsError('the server sent an alert', { + level: plain[0], + description: plain[1] + }) + } + throw tlsError('an unexpected record', { type: record.type }) + } + }, + write: async (bytes) => { + for (let start = 0; start < bytes.length; start += MAX_FRAGMENT_BYTES) + await connection.write( + sealRecord( + keys.send, + ContentType.ApplicationData, + bytes.subarray(start, start + MAX_FRAGMENT_BYTES) + ) + ) + }, + startTls: async () => { + throw tlsError('already a TLS connection') + }, + close: async () => { + if (isClosed) return + isClosed = true + try { + await connection.write( + sealRecord( + keys.send, + ContentType.Alert, + new Uint8Array([1, AlertDescription.CloseNotify]) + ) + ) + } catch { + // The other side may be gone already; closing goes on. + } + await connection.close() + } + } +} diff --git a/packages/device/src/infrastructure/tls-psk/constants.ts b/packages/device/src/infrastructure/tls-psk/constants.ts new file mode 100644 index 00000000..503f7e92 --- /dev/null +++ b/packages/device/src/infrastructure/tls-psk/constants.ts @@ -0,0 +1,43 @@ +/** TLS 1.2 record content types (RFC 5246 §6.2.1). */ +export const ContentType = { + ChangeCipherSpec: 20, + Alert: 21, + Handshake: 22, + ApplicationData: 23 +} as const + +/** Handshake message types used by a TLS 1.2 PSK client. */ +export const HandshakeType = { + ClientHello: 1, + ServerHello: 2, + ServerKeyExchange: 12, + ServerHelloDone: 14, + ClientKeyExchange: 16, + Finished: 20 +} as const + +export const TLS_1_2 = 0x03_03 + +/** TLS_PSK_WITH_AES_128_GCM_SHA256 (RFC 5487): one that iOS's remote pairing tunnel accepts. */ +export const PSK_AES_128_GCM_SHA256 = 0x00_a8 + +/** Extensions: extended master secret (RFC 7627) and secure renegotiation (RFC 5746), as common clients send. */ +export const EXTENDED_MASTER_SECRET = 0x00_17 +export const RENEGOTIATION_INFO = 0xff_01 + +export const RANDOM_BYTES = 32 +export const MASTER_SECRET_BYTES = 48 +export const VERIFY_DATA_BYTES = 12 +export const KEY_BYTES = 16 +export const FIXED_IV_BYTES = 4 +export const EXPLICIT_NONCE_BYTES = 8 +export const TAG_BYTES = 16 +export const RECORD_HEADER_BYTES = 5 +/** Most plaintext per record (RFC 5246 §6.2.1). */ +export const MAX_FRAGMENT_BYTES = 16_384 +/** Most ciphertext a record may carry: the plaintext limit plus room for the nonce and tag. */ +export const MAX_RECORD_BYTES = MAX_FRAGMENT_BYTES + 2048 + +export const AlertDescription = { + CloseNotify: 0 +} as const diff --git a/packages/device/src/infrastructure/tls-psk/handshake.ts b/packages/device/src/infrastructure/tls-psk/handshake.ts new file mode 100644 index 00000000..cac81227 --- /dev/null +++ b/packages/device/src/infrastructure/tls-psk/handshake.ts @@ -0,0 +1,253 @@ +// The client side of a TLS 1.2 PSK handshake (RFC 4279, RFC 5246 §7), for TLS_PSK_WITH_AES_128_GCM_SHA256 with +// the extended master secret (RFC 7627) when the server agrees: ClientHello → ServerHello, [ServerKeyExchange], +// ServerHelloDone → ClientKeyExchange (empty identity), ChangeCipherSpec, Finished → ChangeCipherSpec, Finished. +import { sha256 } from '@noble/hashes/sha2.js' + +import { + ContentType, + EXTENDED_MASTER_SECRET, + FIXED_IV_BYTES, + HandshakeType, + KEY_BYTES, + MASTER_SECRET_BYTES, + PSK_AES_128_GCM_SHA256, + RANDOM_BYTES, + RENEGOTIATION_INFO, + TLS_1_2, + VERIFY_DATA_BYTES +} from '@device/infrastructure/tls-psk/constants.ts' +import { prf } from '@device/infrastructure/tls-psk/prf.ts' +import { + encodeRecord, + openRecord, + sealRecord, + tlsError +} from '@device/infrastructure/tls-psk/records.ts' +import type { + HandshakeIo, + HandshakeMessage, + HandshakeResult, + ServerHello, + TlsRecord +} from '@device/infrastructure/tls-psk/types.ts' +import { ByteReader, ByteWriter, concatBytes } from '@ipaforge/kernel' + +const handshakeMessage = (type: number, body: Uint8Array): Uint8Array => + new ByteWriter() + .u8(type) + .u8(body.length >> 16) + .u16be(body.length & 0xff_ff) + .bytes(body) + .toBytes() + +const clientHello = (random: Uint8Array): Uint8Array => { + const extensions = new ByteWriter() + .u16be(EXTENDED_MASTER_SECRET) + .u16be(0) + .u16be(RENEGOTIATION_INFO) + .u16be(1) + .u8(0) + .toBytes() + + return handshakeMessage( + HandshakeType.ClientHello, + new ByteWriter() + .u16be(TLS_1_2) + .bytes(random) + .u8(0) // no session id + .u16be(2) + .u16be(PSK_AES_128_GCM_SHA256) + .u8(1) + .u8(0) // null compression + .u16be(extensions.length) + .bytes(extensions) + .toBytes() + ) +} + +const alertError = (record: TlsRecord) => + tlsError('the server sent an alert', { + level: record.fragment[0], + description: record.fragment[1] + }) + +/** Reads handshake messages, however records split or join them. */ +const createMessageReader = (readRecord: HandshakeIo['readRecord']) => { + let buffer: Uint8Array = new Uint8Array(0) + + return async (): Promise => { + for (;;) { + if (buffer.length >= 4) { + const length = + ((buffer[1] ?? 0) << 16) | ((buffer[2] ?? 0) << 8) | (buffer[3] ?? 0) + if (buffer.length >= 4 + length) { + const raw = buffer.slice(0, 4 + length) + buffer = buffer.slice(4 + length) + return { type: raw[0] ?? 0, body: raw.subarray(4), raw } + } + } + const record = await readRecord() + if (!record) + throw tlsError('the server closed the connection during the handshake') + if (record.type === ContentType.Alert) throw alertError(record) + if (record.type !== ContentType.Handshake) + throw tlsError('an unexpected record during the handshake', { + type: record.type + }) + buffer = concatBytes([buffer, record.fragment]) + } + } +} + +const readServerHello = (body: Uint8Array): ServerHello => { + const reader = new ByteReader(body) + const version = reader.u16be() + const random = reader.bytes(RANDOM_BYTES) + reader.skip(reader.u8()) // session id + const suite = reader.u16be() + reader.skip(1) // compression + if (version !== TLS_1_2 || suite !== PSK_AES_128_GCM_SHA256) + throw tlsError('the server chose another version or cipher suite', { + version, + suite + }) + let extendedMasterSecret = false + if (reader.remaining >= 2) { + const end = reader.u16be() + reader.position + while (reader.position < end) { + const type = reader.u16be() + reader.skip(reader.u16be()) + if (type === EXTENDED_MASTER_SECRET) extendedMasterSecret = true + } + } + return { random, extendedMasterSecret } +} + +/** RFC 4279 §2: the premaster secret for a plain PSK is N zero bytes and the N-byte key, each with its length. */ +const premasterFor = (psk: Uint8Array): Uint8Array => + new ByteWriter() + .u16be(psk.length) + .bytes(new Uint8Array(psk.length)) + .u16be(psk.length) + .bytes(psk) + .toBytes() + +const keysFrom = ( + master: Uint8Array, + clientRandom: Uint8Array, + serverRandom: Uint8Array +) => { + const block = prf( + master, + 'key expansion', + concatBytes([serverRandom, clientRandom]), + 2 * KEY_BYTES + 2 * FIXED_IV_BYTES + ) + const at = (start: number, length: number) => + block.slice(start, start + length) + + return { + send: { + key: at(0, KEY_BYTES), + fixedIv: at(2 * KEY_BYTES, FIXED_IV_BYTES), + sequence: 0n + }, + receive: { + key: at(KEY_BYTES, KEY_BYTES), + fixedIv: at(2 * KEY_BYTES + FIXED_IV_BYTES, FIXED_IV_BYTES), + sequence: 0n + } + } +} + +const sameBytes = (a: Uint8Array, b: Uint8Array): boolean => { + let difference = a.length ^ b.length + for (let index = 0; index < Math.min(a.length, b.length); index++) + difference |= (a[index] ?? 0) ^ (b[index] ?? 0) + return difference === 0 +} + +export const handshake = async ( + { readRecord, write, randomBytes }: HandshakeIo, + psk: Uint8Array +): Promise => { + const transcript: Uint8Array[] = [] + const hashed = () => sha256(concatBytes(transcript)) + const clientRandom = randomBytes(RANDOM_BYTES) + + const hello = clientHello(clientRandom) + transcript.push(hello) + await write(encodeRecord(ContentType.Handshake, hello)) + + const nextMessage = createMessageReader(readRecord) + const serverHelloMessage = await nextMessage() + if (serverHelloMessage.type !== HandshakeType.ServerHello) + throw tlsError('the server did not answer with ServerHello', { + type: serverHelloMessage.type + }) + transcript.push(serverHelloMessage.raw) + const serverHello = readServerHello(serverHelloMessage.body) + for (;;) { + const message = await nextMessage() + transcript.push(message.raw) + if (message.type === HandshakeType.ServerHelloDone) break + // A ServerKeyExchange only carries an identity hint for PSK; nothing to do with it. + if (message.type !== HandshakeType.ServerKeyExchange) + throw tlsError('an unexpected handshake message', { type: message.type }) + } + + // An empty PSK identity: the key itself is what both sides share. + const keyExchange = handshakeMessage( + HandshakeType.ClientKeyExchange, + new Uint8Array([0, 0]) + ) + transcript.push(keyExchange) + const premaster = premasterFor(psk) + const master = serverHello.extendedMasterSecret + ? prf(premaster, 'extended master secret', hashed(), MASTER_SECRET_BYTES) + : prf( + premaster, + 'master secret', + concatBytes([clientRandom, serverHello.random]), + MASTER_SECRET_BYTES + ) + const keys = keysFrom(master, clientRandom, serverHello.random) + + const finished = handshakeMessage( + HandshakeType.Finished, + prf(master, 'client finished', hashed(), VERIFY_DATA_BYTES) + ) + await write( + concatBytes([ + encodeRecord(ContentType.Handshake, keyExchange), + encodeRecord(ContentType.ChangeCipherSpec, new Uint8Array([1])), + sealRecord(keys.send, ContentType.Handshake, finished) + ]) + ) + transcript.push(finished) + + const changeCipherSpec = await readRecord() + if (changeCipherSpec?.type === ContentType.Alert) + throw alertError(changeCipherSpec) + if (changeCipherSpec?.type !== ContentType.ChangeCipherSpec) + throw tlsError('the server did not change cipher spec', { + type: changeCipherSpec?.type + }) + const serverFinishedRecord = await readRecord() + if ( + !serverFinishedRecord || + serverFinishedRecord.type !== ContentType.Handshake + ) + throw tlsError('the server did not finish the handshake') + const serverFinished = openRecord(keys.receive, serverFinishedRecord) + const expected = handshakeMessage( + HandshakeType.Finished, + prf(master, 'server finished', hashed(), VERIFY_DATA_BYTES) + ) + if (!sameBytes(serverFinished, expected)) + throw tlsError( + "the server's Finished doesn't match: it doesn't hold the same key" + ) + + return keys +} diff --git a/packages/device/src/infrastructure/tls-psk/prf.ts b/packages/device/src/infrastructure/tls-psk/prf.ts new file mode 100644 index 00000000..096737d6 --- /dev/null +++ b/packages/device/src/infrastructure/tls-psk/prf.ts @@ -0,0 +1,23 @@ +// The TLS 1.2 pseudorandom function with SHA-256 (RFC 5246 §5): P_SHA256(secret, label + seed). +import { hmac } from '@noble/hashes/hmac.js' +import { sha256 } from '@noble/hashes/sha2.js' + +import { concatBytes, utf8Encode } from '@ipaforge/kernel' + +export const prf = ( + secret: Uint8Array, + label: string, + seed: Uint8Array, + length: number +): Uint8Array => { + const labelSeed = concatBytes([utf8Encode(label), seed]) + const out = new Uint8Array(length) + let a = labelSeed + for (let filled = 0; filled < length; ) { + a = hmac(sha256, secret, a) + const block = hmac(sha256, secret, concatBytes([a, labelSeed])) + out.set(block.subarray(0, length - filled), filled) + filled += block.length + } + return out +} diff --git a/packages/device/src/infrastructure/tls-psk/records.ts b/packages/device/src/infrastructure/tls-psk/records.ts new file mode 100644 index 00000000..8c414acd --- /dev/null +++ b/packages/device/src/infrastructure/tls-psk/records.ts @@ -0,0 +1,114 @@ +// TLS 1.2 records: reading them from a connection, and AES-128-GCM protection once ChangeCipherSpec is done +// (RFC 5288: nonce = 4-byte fixed IV + 8-byte explicit nonce, additional data = sequence, type, version, length). +import { gcm } from '@noble/ciphers/aes.js' + +import type { Connection } from '@device/domain/ports/types.ts' +import { createStreamReader } from '@device/infrastructure/framing/stream-reader.ts' +import { + EXPLICIT_NONCE_BYTES, + MAX_RECORD_BYTES, + RECORD_HEADER_BYTES, + TAG_BYTES, + TLS_1_2 +} from '@device/infrastructure/tls-psk/constants.ts' +import type { + RecordKeys, + TlsRecord +} from '@device/infrastructure/tls-psk/types.ts' +import { + ByteWriter, + concatBytes, + ErrorCode, + IPAForgeError +} from '@ipaforge/kernel' + +export const tlsError = (message: string, data?: Record) => + new IPAForgeError(ErrorCode.DeviceProtocolError, { + message: `TLS-PSK: ${message}`, + ...(data ? { data } : {}) + }) + +export const encodeRecord = (type: number, fragment: Uint8Array): Uint8Array => + new ByteWriter() + .u8(type) + .u16be(TLS_1_2) + .u16be(fragment.length) + .bytes(fragment) + .toBytes() + +/** Reads whole records from `connection`; `null` once it ends between records. */ +export const createRecordReader = (connection: Connection) => { + const reader = createStreamReader(connection) + + return async (): Promise => { + let header: Uint8Array + try { + header = await reader.readExact(RECORD_HEADER_BYTES) + } catch (error) { + if ( + error instanceof IPAForgeError && + error.code === ErrorCode.DeviceDisconnected + ) + return null + throw error + } + const view = new DataView(header.buffer, header.byteOffset) + const length = view.getUint16(3) + if (length > MAX_RECORD_BYTES) + throw tlsError('a record too large', { length }) + + return { type: header[0] ?? 0, fragment: await reader.readExact(length) } + } +} + +const additionalData = (sequence: bigint, type: number, length: number) => + new ByteWriter() + .u64be(sequence) + .u8(type) + .u16be(TLS_1_2) + .u16be(length) + .toBytes() + +export const sealRecord = ( + keys: RecordKeys, + type: number, + plain: Uint8Array +): Uint8Array => { + const explicit = new ByteWriter().u64be(keys.sequence).toBytes() + const nonce = concatBytes([keys.fixedIv, explicit]) + const sealed = gcm( + keys.key, + nonce, + additionalData(keys.sequence, type, plain.length) + ).encrypt(plain) + keys.sequence += 1n + + return encodeRecord(type, concatBytes([explicit, sealed])) +} + +export const openRecord = (keys: RecordKeys, record: TlsRecord): Uint8Array => { + const { fragment, type } = record + if (fragment.length < EXPLICIT_NONCE_BYTES + TAG_BYTES) + throw tlsError('a record too short to open') + const nonce = concatBytes([ + keys.fixedIv, + fragment.subarray(0, EXPLICIT_NONCE_BYTES) + ]) + const sealed = fragment.subarray(EXPLICIT_NONCE_BYTES) + const length = sealed.length - TAG_BYTES + let plain: Uint8Array + try { + plain = gcm( + keys.key, + nonce, + additionalData(keys.sequence, type, length) + ).decrypt(sealed) + } catch { + throw tlsError( + "a record that doesn't open (wrong key, or changed on the way)" + ) + } + keys.sequence += 1n + + return plain +} diff --git a/packages/device/src/infrastructure/tls-psk/types.ts b/packages/device/src/infrastructure/tls-psk/types.ts new file mode 100644 index 00000000..9f12ab39 --- /dev/null +++ b/packages/device/src/infrastructure/tls-psk/types.ts @@ -0,0 +1,34 @@ +export type TlsRecord = { + readonly type: number + readonly fragment: Uint8Array +} + +/** One direction's record protection after ChangeCipherSpec: AES-128-GCM key, fixed IV and sequence number. */ +export type RecordKeys = { + readonly key: Uint8Array + readonly fixedIv: Uint8Array + sequence: bigint +} + +export type HandshakeMessage = { + readonly type: number + readonly body: Uint8Array + /** Header and body, as the transcript hashes it. */ + readonly raw: Uint8Array +} + +export type HandshakeIo = { + readonly readRecord: () => Promise + readonly write: (bytes: Uint8Array) => Promise + readonly randomBytes: (length: number) => Uint8Array +} + +export type HandshakeResult = { + readonly send: RecordKeys + readonly receive: RecordKeys +} + +export type ServerHello = { + readonly random: Uint8Array + readonly extendedMasterSecret: boolean +}