Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/desktop/scripts/device-probe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 [<signed.ipa>] [--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.
Expand Down
79 changes: 79 additions & 0 deletions apps/desktop/src/main/adapters/network/tls-psk.test.ts
Original file line number Diff line number Diff line change
@@ -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' })
})
})
4 changes: 3 additions & 1 deletion apps/desktop/src/probes/device/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand All @@ -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)
})
62 changes: 62 additions & 0 deletions apps/desktop/src/probes/device/commands/wifi-tunnel.ts
Original file line number Diff line number Diff line change
@@ -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<void> =>
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()
}
})
4 changes: 2 additions & 2 deletions docs/design/roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions docs/device.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, `<service>.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 |
Expand Down Expand Up @@ -119,6 +131,7 @@ pnpm --filter @ipaforge/desktop device-probe pairing-status <TEAMID...> # 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 <udid>] # finds known devices on Wi-Fi, without usbmuxd
pnpm --filter @ipaforge/desktop device-probe rp-tunnel [--udid <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 <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 [<signed.ipa>] [--mb 100] [--compare] # a timed upload and install through the tunnel
Expand Down
2 changes: 1 addition & 1 deletion docs/roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
81 changes: 80 additions & 1 deletion packages/device/src/__tests__/fake-remote-device.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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<string, unknown>[] = []
let fromHost = 0
let toHost = 0
const errorRecord = () => pairingData([[TlvType.Error, new Uint8Array([2])]])

const setupStep = (tlv: ReadonlyMap<number, Uint8Array>) => {
Expand Down Expand Up @@ -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([
Expand Down Expand Up @@ -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<string, unknown>)
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<string, unknown>
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
}
}
Loading
Loading