diff --git a/README.md b/README.md index c37ab28..586fc9d 100644 --- a/README.md +++ b/README.md @@ -23,13 +23,25 @@ are green, `mwb --version` / `--check-permissions` run. Lanes run one at a time in the order of [`docs/loop.md`](docs/loop.md) §6; `packet-codec` is next. There are no test suites by design: the user tests the app. +2026-09-16: all lanes through `extras` merged; checkpoints CP1–CP3 with +the user. The `polish` lane is now working the findings from that +testing ([`docs/features/polish/README.md`](docs/features/polish/README.md)). +P1 of it matters to anyone pairing with a PC: **the encryption changed +in PowerToys 0.101**, and a machine on stable PowerToys still speaks the +older scheme, so `MacCipherScheme` defaults to `legacy` and the Security +pane's "Encryption compatibility" picker is the switch to change if the +menu says a machine has the wrong one (protocol +[§2.5](docs/protocol.md)). The legacy handshake is the one part of this +protocol confirmed against a real Windows peer rather than against the +source (§10.9). + ## Decisions | # | Decision | Why | |---|---|---| | D1 | **Swift 6 + SwiftPM, no Xcode project.** The `.app` bundle is assembled by `tools/bundle.sh`. | Every platform surface the port needs (event taps, event posting, pasteboard, displays, Network.framework, menu bar) is an Apple framework; a second language would add an FFI boundary for nothing. Rust was considered for the protocol core and rejected as a second build system with no consumer that needs it. | | D2 | **Three targets, layered by import rules.** `MWBCore` (Foundation + CommonCrypto only; sans-I/O protocol state machines), `MWBNet` (Network.framework), `MWBMac` (AppKit/CoreGraphics), executable `mwb`. | Protocol, crypto, matrix and coordinate logic stay readable and reviewable without any platform code around them. SwiftPM target boundaries make the layering a build failure rather than a convention. | -| D3 | **Settings file mirrors the PowerToys schema** (`{"name":"MouseWithoutBorders","version":"1.1","properties":{...}}`, same property names and defaults) at `~/Library/Application Support/mwb-mac/settings.json`, mode 0600. Key stored in plaintext like Windows. | Boring and copy-pasteable between machines. Keychain storage for the key is a backlog item, not a v1 blocker; the threat model equals the Windows one. | +| D3 | **Settings file mirrors the PowerToys schema** (`{"name":"MouseWithoutBorders","version":"1.1","properties":{...}}`, same property names and defaults) at `~/Library/Application Support/mwb-mac/settings.json`, mode 0600. Key stored in plaintext like Windows. Properties Windows writes and this port does not implement are round-tripped untouched. **One property is ours alone**: `MacCipherScheme` (`"legacy"` \| `"modern"`), because the wire has no way to ask a peer which encryption scheme it speaks (protocol §2.5) and Windows has no such switch — its build decides. A PowerToys that rewrites the file drops the key and the default, `legacy`, applies again. | Boring and copy-pasteable between machines. Keychain storage for the key is a backlog item, not a v1 blocker; the threat model equals the Windows one. A second settings file for one Mac-only property would be worse than one unknown key in a file that already tolerates unknown keys. | | D4 | **Key mapping: Win↔Command, Alt↔Option, Ctrl↔Control**, with a static Windows-VK ↔ macOS-keycode table in `MWBCore/KeyMap.swift`. | Windows sends virtual-key codes only (protocol §5.1). A layout-independent table is the only thing both sides can agree on; a "swap Cmd/Ctrl when controlling Windows" option comes later. | | D5 | **Permissions are the user's.** The app needs Accessibility (to post and swallow events) and Input Monitoring (to listen). It detects and explains; it never scripts System Settings. The binary must carry a **stable code-signing identity** (self-signed certificate at minimum) or TCC forgets the grant on every rebuild. | macOS TCC keys grants by code signature. Ad-hoc signatures change per build. | | D6 | **Out of scope for v1**: Windows service / logon-screen control, Explorer drag-and-drop, screen capture to Paint, GPO, telemetry, key propagation via `Heartbeat_ex`, the animated fake cursor (`DrawMouse`). | No macOS equivalent, or Windows-shell specific, or not needed to join a matrix. Listed in TODO §9 with reasons. | @@ -43,7 +55,8 @@ Sources/ Packet.swift DATA layout, PackageType, big/small rule (§1.1-1.2) Framing.swift magic + checksum encode/validate (§1.3) MagicHash.swift Get24BitHash (§2.1) - CipherStream.swift PBKDF2 + AES-256-CBC zero-padding stream codec (§2.2-2.3) + CipherStream.swift PBKDF2 + AES-256-CBC zero-padding stream codec, + legacy and modern schemes (§2.2-2.5) Session.swift handshake / dedup / heartbeat state machine, sans-I/O: bytes in, (packets, actions) out (§1.4, §3.2-3.3) Matrix.swift 4-slot matrix, pool, LiveMachineMatrix (§4.1-4.2) diff --git a/TODO.md b/TODO.md index 3f12a4e..53f61f1 100644 --- a/TODO.md +++ b/TODO.md @@ -224,10 +224,20 @@ concurrency, shared constants, checkpoints) is fixed in `docs/contracts.md`. - [ ] Each finding from the user becomes a line here with the file that owns the fix. Findings and decisions: `docs/features/polish/README.md`. -- [ ] **P1** legacy cipher scheme (PowerToys ≤ 0.100) with a +- [x] **P1** legacy cipher scheme (PowerToys ≤ 0.100) with a `MacCipherScheme` setting defaulting to legacy, plus the scheme-mismatch diagnostic — `CipherStream.swift`, `Settings.swift`, `PeerConnection.swift`, `BulkConnection.swift`, `SecurityPane.swift`. + Also `Session.swift` (`InvalidKeyReason.cipherSchemeMismatch`, + `SocketStatus.cipherSchemeMismatch`), `ChannelConfig.swift`, + `BulkChannel.swift` (`BulkConfig.cipherScheme`), `StatusItem.swift`, + `EngineActions.swift`, `ClipboardBridge.swift`; protocol §2.5 and + §10.9, README D3 and §Status. Legacy constants verified offline + against Python `cryptography` in both directions. +- [ ] **P1 follow-up** (app-ui): `UIBridge.updateNotifications` posts no + notification for `.cipherSchemeMismatch` — it only tests + `status == .invalidKey` (`UIBridge.swift:198-200`). One `else if`; + requested in the polish README Handshakes. - [ ] Extras follow-ups: document that Windows pokes the idle timer only when local input is idle (`Common.cs:561-572`) — ours renews on every `Awake` (§10.8 note 1); publish `EventTap.easyMouseKeyDown` diff --git a/docs/features/polish/README.md b/docs/features/polish/README.md index d036190..d5dd0d8 100644 --- a/docs/features/polish/README.md +++ b/docs/features/polish/README.md @@ -73,14 +73,104 @@ user had not granted Accessibility yet; the menu says so. No code change unless the user reports the menu text was unclear. Kept here so the CP1 record is complete. +## Handshakes + +*Requests to other lanes, raised by P1 and deliberately not made here.* + +1. **app-ui / app-engine — the notification for a scheme mismatch.** + `UIBridge.updateNotifications` fires `notifier.invalidKey(for:)` on + `status == .invalidKey` only (`Sources/mwb/UIBridge.swift:198-200`), so a + `.cipherSchemeMismatch` row shows in the menu but posts no notification. + One `else if` in that method would fix it; `UIBridge.swift` is not in this + item's file list, so it is a request rather than an edit. + ## Status / TODO -- [ ] P1: legacy scheme + setting + diagnostic, files as listed; +- [x] P1: legacy scheme + setting + diagnostic, files as listed; `docs/protocol.md` §2.5 and §10.9. - [ ] P2: none. ## Work log +**2026-09-16 — Dev (P1).** Implemented as decided above. + +*Offline first.* Before any app code, the legacy constants were checked +against an independent implementation, in the scratchpad: our +`CipherWriter(scheme: .legacy)` stream decrypts under Python +`cryptography`'s AES-CBC with +`hashlib.pbkdf2_hmac('sha512', key, '18446744073709551615'.encode('utf-16-le'), 50000, 32)` +and IV `b"1844674407370955"`, and our `CipherReader(scheme: .legacy)` +recovers a stream Python encrypted the same way. Both directions matched +byte for byte, and the derived key and IV matched Python's before either +stream was built. No socket was opened and the app was not launched. + +*What changed.* + +- `Sources/MWBCore/CipherStream.swift`: a `CipherScheme` enum + (`.legacy` default, `.modern`) with `preambleSize` and `other`; + `LegacyCipherConstants` carrying the fixed salt (UTF-16LE of + `"18446744073709551615"`, 40 bytes, `Encryption.cs:126` + + `Common.cs:407-410`), 50 000 iterations (`:127`) and the ASCII IV + (`GenLegalIV`, `:140-154`), all cited to the pre-`a9e1f0f20e` file; + `deriveStreamKey` takes the iteration count; a `StreamMaterial` value + computes key/IV/cleartext-header per scheme for each side. + `CipherWriter.header` is now 16 bytes under `.legacy` (the encrypted + sacrificial block alone) and 48 under `.modern`; `CipherReader` + consumes a cleartext header only when the scheme has one. +- `Sources/MWBCore/Settings.swift`: `MacCipherScheme` in the defaults and + a `macCipherScheme: CipherScheme` accessor, default `.legacy`. +- `Sources/MWBCore/Session.swift`: `InvalidKeyReason.cipherSchemeMismatch` + and a `SocketStatus.cipherSchemeMismatch` case. The status case has raw + value **100**, outside the Windows 0–9 range, so the Windows numbering + the menu colours depend on is untouched; nothing serialises this enum. +- `Sources/MWBNet/ChannelConfig.swift`, `BulkChannel.swift`: both configs + carry the scheme; a change to it triggers `needsFullReopen`, like a key + or port change. +- `Sources/MWBNet/PeerConnection.swift`: writer, reader and the preamble + read all take the scheme (`cipherScheme.preambleSize`, replacing the + hard-coded 48). The diagnostic keeps the peer's raw opening bytes and + the plaintext they yielded until one packet frames; if the first packet + fails framing under our scheme *and* the same raw bytes frame under the + other, the connection closes `.invalidKey(.cipherSchemeMismatch)` and + reports the matching status. Nothing is fed to the `Session` on that + path (invariant 2). +- `Sources/MWBNet/BulkConnection.swift`: takes the scheme. **No + diagnostic there** — a bulk transfer only begins with a peer whose + control connection already framed under the configured scheme + (`BulkSink.authorise`), so a mismatch has already been reported. +- `Sources/MWBMac/StatusItem.swift`: the new status is painted the + invalid-key brown (same kind of failure) with its own words, "wrong + encryption compatibility setting". +- `Sources/MWBMac/SettingsWindow/SecurityPane.swift`: an "Encryption + compatibility" radio group, "PowerToys 0.100 and earlier" / + "PowerToys 0.101 and later", bound straight through + `SettingsViewModel.binding`. Not a draft like the key and port: one + click is a whole change. +- `Sources/mwb/EngineActions.swift` and `Sources/mwb/ClipboardBridge.swift` + map `settings.macCipherScheme` into `ChannelConfig` / `BulkConfig`. The + brief said `Engine.swift`; those two files are where `channelConfig()` + and `bulkConfig()` actually live (both are `Engine` extensions). +- `docs/protocol.md` §2.5 and §10.9, `README.md` D3 + §Status + the + architecture line for `CipherStream.swift`, `TODO.md` §10. + +*Deviations and decisions worth flagging to the lead.* + +1. Two files outside the stated list were touched, each additively and by + necessity: `Sources/MWBNet/BulkChannel.swift` (the `cipherScheme` + field on `BulkConfig` — `BulkConnection` cannot be handed a scheme + without it) and `Sources/mwb/ClipboardBridge.swift` (where + `bulkConfig()` is built). +2. The diagnostic needs up to 48 + 32 raw bytes, not one packet's worth. + Configured `.legacy` against a `.modern` peer, our reader treats the + peer's first 16 bytes as the sacrificial block, so the first 32 bytes + of plaintext appear after only 48 raw bytes — too few to re-run the + modern reader, which wants 32 header bytes before it decrypts + anything. The probe therefore waits for `diagnosticBytes` before + replaying. While it waits, the garbage keeps spending the session's + untrusted budget exactly as it would without the diagnostic, and + Windows sends ten handshakes at once, so the bytes are always there. +3. The notification gap in Handshakes 1 above. + ## QA log ## Review diff --git a/docs/protocol.md b/docs/protocol.md index 147c9ef..c706775 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -163,6 +163,9 @@ Zero padding never adds bytes because every write is a multiple of 16. Framing is therefore entirely length-driven by `Type` (§1.1). The clipboard channel (§5.3) uses the same layout. +**This is the v0.101 layout only.** Every PowerToys up to v0.100.2 uses +the fixed salt and IV of §2.5 instead, with no cleartext header. + ### 2.4 The security key - Minimum 16 characters; validation is length-only (`Encryption.cs:235-242`). @@ -172,6 +175,65 @@ clipboard channel (§5.3) uses the same layout. - Stored in **plaintext** in `settings.json` as `SecurityKey` (`Class/Setting.cs:479-511`); a key change reopens all sockets. +### 2.5 Legacy stream, PowerToys ≤ 0.100 **[verified against a real Windows peer]** + +§2.2 and §2.3 describe **v0.101 and later** only. PR #48742 +(`a9e1f0f20e`, 2026-06-22) replaced a fixed salt and IV with the +per-connection cleartext header; every release up to and including +**v0.100.2** (2026-06-26) — which is what a machine on stable PowerToys +still runs today — uses the fixed material below. Citations in this +section are to the pre-change file: +`git show a9e1f0f20e^:src/modules/MouseWithoutBorders/App/Core/Encryption.cs`. + +- `InitialIV = ulong.MaxValue.ToString(InvariantCulture)` = + `"18446744073709551615"` (`Encryption.cs:41`). +- Key = `PBKDF2-HMAC-SHA512(password: MyKey (UTF-8), salt: + Common.GetBytesU(InitialIV), iterations: 50 000, length: 32)` + (`Encryption.cs:117-138`, the call at `:124-129`). `GetBytesU` is + `Encoding.Unicode`, i.e. **UTF-16LE** (`Common.cs:407-410`), so the + salt is 40 bytes — `31 00 38 00 34 00 … 35 00` — not the 20 ASCII + digits. Note the iteration count: 50 000, half the modern 100 000. +- IV = `GenLegalIV` (`Encryption.cs:140-154`): `InitialIV` cut to the + 16-byte block size and taken as **ASCII** (`Common.GetBytes`, + `Common.cs:397-400`) — `"1844674407370955"`. +- Cipher configuration is unchanged from §2.2: AES-256-CBC, + `PaddingMode.Zeros`, 16-byte blocks (`Encryption.cs:93-113`). +- **No cleartext header.** Each direction is simply: + +``` +[16 bytes random] FIRST ciphertext block: the sacrificial block, + written through the cipher and discarded by the reader + (Common.cs:1528-1558, wired at SocketStuff.cs:104-105, 118-119) +[32 or 64 byte packets ...] framed as §1.3 +``` + +The sacrificial block exists *because* the IV is fixed: without it the +first real packet would be the block a constant IV protects directly, so +identical first packets would encrypt identically. The header scheme kept +the block even though a random IV makes it redundant. + +Everything else is the same across the two schemes — the magic number +(§2.1), the framing (§1.3), the packet layout (§1.1), the handshake +(§3.2) and the bulk channel's own stream (§6.3), which uses whichever +scheme the control channel does. + +**Which one this port speaks.** The Mac-only `MacCipherScheme` setting, +`"legacy"` (default) or `"modern"`, chosen in the Security pane as +"Encryption compatibility". There is no auto-negotiation and there cannot +be a useful one: both vintages of Windows write their preamble first and +never adapt, so two auto-detecting machines would each wait for the other. + +**Mismatch diagnostic.** There is no MAC anywhere in this protocol +(§1.3), so a peer on the other scheme is indistinguishable from a peer +with the wrong key: garbage plaintext, failed framing. When the first +packet fails framing under the configured scheme, the reader replays the +peer's raw opening bytes — up to 48 + 32, the longest preamble plus one +packet — under the other scheme; if *that* frames, the key is right and +the setting is wrong, and the connection ends as +`InvalidKeyReason.cipherSchemeMismatch` with its own status row rather +than as "wrong security key". One extra AES setup on a connection that +was already failing, and nothing at all on a connection that works. + --- ## 3. Connections and handshake — `Class/SocketStuff.cs` @@ -1173,3 +1235,40 @@ sees them. One subsection per lane, appended, never rewritten. `ClipboardBridge` has no equivalent, which means a second copy of identical content after a switch may be dropped where Windows would resend it — recorded here rather than fixed, since it is the clipboard lane's state. + +### 10.9 polish — P1, the legacy stream, verified against a real Windows peer (2026-09-16) + +The first fact in this document confirmed against a live, unmodified +Windows machine rather than against the source alone. + +**The peer.** The user's PC `Lu-Corsair` (10.233.33.52), running stable +PowerToys, accepting TCP on 15101. Under our then-only scheme (§2.3, +the cleartext header) every packet it sent decrypted to garbage and +every packet we sent was ignored. + +**The probe.** An independent Python re-implementation of §1–§3 in the +lead's scratchpad — written from this document, not from the Swift — +reproduced the whole handshake against that PC with the **legacy** +scheme of §2.5 and got, in order: + +1. ten `Handshake (126)` packets whose `MachineName` was `Lu-Corsair`, + each framing cleanly under the magic derived from the shared key; +2. a `HandshakeAck (127)` whose `Machine1..4` were the bitwise + complement of the nonce the probe had sent; +3. `Heartbeat_ex (51)` — i.e. the PC had marked the probe trusted and + moved on to ordinary traffic. + +**What that proves.** `Framing` (§1.3), `MagicHash` (§2.1), the packet +layout (§1.1) and the handshake (§3.2) are correct as transcribed — +they are exercised end to end by that exchange. The only thing that was +wrong was the stream cipher's key, IV and preamble, which is exactly +what §2.5 now records. + +**What it does not prove.** Nothing about the `.modern` scheme, which +has still only been transcribed: no v0.101 machine has been on the wire +with us. And the run was a *probe*, not this port — the Swift side of +§2.5 was checked separately, offline, by encrypting with `CipherWriter` +and decrypting with Python's `cryptography` under +`pbkdf2_hmac('sha512', key, '18446744073709551615'.encode('utf-16-le'), +50000, 32)` and `AES-CBC("1844674407370955")`, and vice versa; both +directions matched byte for byte.