Merge lane/wire-core: DATA packet, framing, magic hash, CBC stream

Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5.1 committed 2026-09-16 00:21:25 -07:00
commit 1ed49d145e
7 files changed
+1163 -35

No files matched your search

+212
View File
@@ -0,0 +1,212 @@
// The per-direction AES-256-CBC stream that every byte of the protocol travels
// through, and the PBKDF2 derivation behind it. See docs/protocol.md §2.2-§2.3.
//
// Ported from App/Core/Encryption.cs (92-171) and
// App/Core/Common.cs SendOrReceiveARandomDataBlockPerInitialIV (1528-1558),
// wired at App/Class/SocketStuff.cs:102-123.
//
// This is the only file in the project that touches CommonCrypto (CLAUDE.md,
// Swift standards): CryptoKit has no CBC mode.
import CommonCrypto
import Foundation
/// A failure in the cipher stream. No case carries key material, salt, IV or
/// plaintext: these values are logged by callers (CLAUDE.md invariant 2).
public enum CipherError: Error, Sendable, Hashable {
/// PBKDF2 refused the password or salt.
case keyDerivationFailed
/// `CCCryptorCreate` failed with this status.
case cryptorCreationFailed(Int32)
/// `CCCryptorUpdate` failed with this status.
case cryptorUpdateFailed(Int32)
}
/// Constants shared by both directions, all dictated by the Windows side.
enum CipherConstants {
/// AES block size in bytes (`SymAlBlockSize`, `Encryption.cs:32`).
static let blockSize = 16
/// PBKDF2 salt length in bytes (`SaltSize`, `Encryption.cs:38`).
static let saltSize = 16
/// PBKDF2 iterations (`KeyDerivationIterations`, `Encryption.cs:42`).
static let iterations: UInt32 = 100_000
/// Derived AES-256 key length in bytes (`DerivedKeyLength`, `Encryption.cs:45`).
static let derivedKeyLength = 32
}
/// `GenLegalKey` (`Encryption.cs:107-115`): PBKDF2-HMAC-SHA512 over the UTF-8
/// bytes of the security key, which is what .NET's `Rfc2898DeriveBytes.Pbkdf2`
/// does with a `string` password.
func deriveStreamKey(from securityKey: String, salt: [UInt8]) throws -> [UInt8] {
let password = Array(securityKey.utf8)
var derived = [UInt8](repeating: 0, count: CipherConstants.derivedKeyLength)
let status = password.withUnsafeBytes { passwordBytes in
salt.withUnsafeBufferPointer { saltBytes in
derived.withUnsafeMutableBufferPointer { out in
CCKeyDerivationPBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
passwordBytes.baseAddress?.assumingMemoryBound(to: CChar.self),
passwordBytes.count,
saltBytes.baseAddress, saltBytes.count,
CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA512),
CipherConstants.iterations,
out.baseAddress, out.count)
}
}
}
guard status == kCCSuccess else { throw CipherError.keyDerivationFailed }
return derived
}
/// `count` cryptographically random bytes.
///
/// `SystemRandomNumberGenerator` is documented as cryptographically secure on
/// Apple platforms, which is what `RandomNumberGenerator.Fill`
/// (`Encryption.cs:125`) promises on the Windows side.
func randomBytes(_ count: Int) -> [UInt8] {
var generator = SystemRandomNumberGenerator()
return (0..<count).map { _ in UInt8.random(in: UInt8.min...UInt8.max, using: &generator) }
}
/// One direction of a CBC stream: a `CCCryptor` that keeps the chaining state
/// and buffers any partial block internally, like .NET's `CryptoStream`.
///
/// `options = 0` means CBC with **no** padding. Windows configures
/// `PaddingMode.Zeros` (`Encryption.cs:96`), but zero padding only ever adds
/// bytes when a stream is closed on a partial block, and every write here is a
/// whole number of 16-byte blocks, so it never fires.
private final class CBCCryptor {
private var cryptor: CCCryptorRef?
init(encrypt: Bool, key: [UInt8], iv: [UInt8]) throws {
var ref: CCCryptorRef?
let status = key.withUnsafeBytes { keyBytes in
iv.withUnsafeBytes { ivBytes in
CCCryptorCreate(
CCOperation(encrypt ? kCCEncrypt : kCCDecrypt),
CCAlgorithm(kCCAlgorithmAES),
CCOptions(0),
keyBytes.baseAddress, keyBytes.count,
ivBytes.baseAddress,
&ref)
}
}
guard status == kCCSuccess, ref != nil else {
throw CipherError.cryptorCreationFailed(status)
}
cryptor = ref
}
deinit {
if let cryptor { CCCryptorRelease(cryptor) }
}
/// Feeds `input` through the cipher and returns whatever complete blocks
/// come out — nothing at all if `input` did not complete a block.
func update(_ input: [UInt8]) throws -> [UInt8] {
guard !input.isEmpty else { return [] }
let capacity = CCCryptorGetOutputLength(cryptor, input.count, false)
var output = [UInt8](repeating: 0, count: capacity)
var moved = 0
let status = input.withUnsafeBytes { inBytes in
output.withUnsafeMutableBufferPointer { outBytes in
CCCryptorUpdate(
cryptor,
inBytes.baseAddress, inBytes.count,
outBytes.baseAddress, outBytes.count,
&moved)
}
}
guard status == kCCSuccess else { throw CipherError.cryptorUpdateFailed(status) }
output.removeLast(capacity - moved)
return output
}
}
/// The sending half of one connection's cipher stream.
///
/// A reference type on purpose: the CBC chaining state is one shared thing per
/// connection, and copying it would silently fork the stream. Not `Sendable` —
/// one connection owns one writer on one queue.
public final class CipherWriter {
private let cryptor: CBCCryptor
/// Everything that must reach the peer before the first packet: the 16-byte
/// salt and 16-byte IV in the clear (`Encryption.cs:124-129`), followed by
/// the encrypted 16-byte sacrificial block
/// (`Common.cs:1528-1541`, written through the cipher stream at
/// `SocketStuff.cs:105`). Send it verbatim, once, before anything else.
public let header: Data
/// Starts a stream under `securityKey` with a fresh random salt and IV.
public init(securityKey: String) throws {
let salt = randomBytes(CipherConstants.saltSize)
let iv = randomBytes(CipherConstants.blockSize)
cryptor = try CBCCryptor(
encrypt: true, key: try deriveStreamKey(from: securityKey, salt: salt), iv: iv)
// The first plaintext block is thrown away by the reader, so that the
// first real packet is never the block the IV directly protects.
let sacrificial = try cryptor.update(randomBytes(CipherConstants.blockSize))
header = Data(salt) + Data(iv) + Data(sacrificial)
}
/// Encrypts `plaintext` and returns the ciphertext to write to the socket.
public func write(_ plaintext: Data) throws -> Data {
Data(try cryptor.update([UInt8](plaintext)))
}
}
/// The receiving half of one connection's cipher stream.
///
/// Consumes the peer's cleartext salt+IV header and the sacrificial block out
/// of the byte stream itself, so the caller only ever hands it socket bytes and
/// gets packet bytes back. Reference type and non-`Sendable` for the same
/// reason as `CipherWriter`.
public final class CipherReader {
private let securityKey: String
private var cryptor: CBCCryptor?
private var headerBytes: [UInt8] = []
private var sacrificialRemaining = CipherConstants.blockSize
/// Prepares to read a stream encrypted under `securityKey`. Nothing is
/// derived until the peer's salt arrives.
public init(securityKey: String) {
self.securityKey = securityKey
}
/// Feeds raw bytes from the socket and returns the packet bytes they
/// yielded, which may be none.
///
/// A wrong key is not detectable here: there is no MAC in this protocol, so
/// the plaintext is simply garbage and `Framing.open` rejects it. Nothing
/// may be acted on before that check (CLAUDE.md invariant 2).
public func read(_ ciphertext: Data) throws -> Data {
var input = [UInt8](ciphertext)
if cryptor == nil {
let wanted = CipherConstants.saltSize + CipherConstants.blockSize
let take = min(wanted - headerBytes.count, input.count)
headerBytes.append(contentsOf: input[0..<take])
input.removeFirst(take)
guard headerBytes.count == wanted else { return Data() }
let salt = Array(headerBytes[0..<CipherConstants.saltSize])
let iv = Array(headerBytes[CipherConstants.saltSize..<wanted])
cryptor = try CBCCryptor(
encrypt: false, key: try deriveStreamKey(from: securityKey, salt: salt), iv: iv)
}
guard let cryptor else { return Data() }
var plaintext = try cryptor.update(input)
if sacrificialRemaining > 0 { // Common.cs:1543-1550
let drop = min(sacrificialRemaining, plaintext.count)
plaintext.removeFirst(drop)
sacrificialRemaining -= drop
}
return Data(plaintext)
}
}
+72
View File
@@ -0,0 +1,72 @@
// The three framing bytes Mouse Without Borders writes over the top of the
// package type: a one-byte checksum and the top 16 bits of the magic number.
// See docs/protocol.md §1.3.
//
// Ported from App/Class/SocketStuff.cs TcpSendData (497-529) and
// ProcessReceivedDataEx (531-556).
import Foundation
/// Sealing and opening the bytes 1..3 that carry the checksum and magic.
///
/// There is no MAC anywhere in this protocol: framing plus the shared-key
/// cipher stream is all that distinguishes a real packet from noise, which is
/// why every caller must treat an `.invalid` packet as hostile.
public enum Framing {
/// The packet's wire bytes with byte 1 set to the checksum and bytes 2..3
/// to the magic number's top 16 bits (`SocketStuff.cs:509-519`).
///
/// The checksum is a plain 8-bit sum of bytes 2..31 **only**, even for a
/// 64-byte packet (`SocketStuff.cs:512-516`): the machine-name half is
/// covered by the cipher, not by the checksum.
public static func seal(_ packet: Packet, magic: UInt32) -> Data {
var bytes = [UInt8](packet.bytes) // always 32 or 64, Packet.bytes
bytes[3] = UInt8(truncatingIfNeeded: (magic >> 24) & 0xFF) // SocketStuff.cs:509
bytes[2] = UInt8(truncatingIfNeeded: (magic >> 16) & 0xFF) // SocketStuff.cs:510
bytes[1] = 0 // SocketStuff.cs:511
bytes[1] = checksum(of: bytes)
return Data(bytes)
}
/// The packet carried by `bytes`, or a packet of type `.invalid` if the
/// magic or the checksum does not match (`SocketStuff.cs:531-556`).
///
/// Bytes 1..3 are zeroed before the packet is built, exactly as
/// `ProcessReceivedDataEx` does (`SocketStuff.cs:553`), which is what makes
/// the package type effectively one byte wide. Validation reads bytes
/// 2..31 only, so it is the same whether the caller passes the first 32
/// bytes or all 64. A receiver therefore does what Windows does
/// (`SocketStuff.cs:578-600`): open the first 32 bytes, and if
/// `type.isBig`, read 32 more and open the concatenation.
public static func open(_ bytes: Data, magic: UInt32) -> Packet {
guard bytes.count == packageSize || bytes.count == packageSizeEx else {
return Packet(type: .invalid)
}
var buf = [UInt8](bytes)
// Only the top 16 bits of the magic number are ever transmitted
// (SocketStuff.cs:537, 539).
let received = (UInt32(buf[3]) << 24) | (UInt32(buf[2]) << 16)
var valid = received == (magic & 0xFFFF_0000)
if buf[1] != checksum(of: buf) { // SocketStuff.cs:545-551
valid = false
}
buf[1] = 0
buf[2] = 0
buf[3] = 0 // SocketStuff.cs:553
if !valid {
buf[0] = PackageType.invalid.rawValue // SocketStuff.cs:542, 550
}
return Packet(bytes: Data(buf)) ?? Packet(type: .invalid)
}
/// 8-bit wrapping sum of bytes 2..31 (`SocketStuff.cs:512-516`).
private static func checksum(of bytes: [UInt8]) -> UInt8 {
var sum: UInt8 = 0
for i in 2..<packageSize {
sum = sum &+ bytes[i]
}
return sum
}
}
+113
View File
@@ -0,0 +1,113 @@
// Everything derived from the security key string itself: the magic number
// that frames every packet, and the key's validity, generation and display
// rules. See docs/protocol.md §2.1 and §2.4.
//
// Ported from App/Core/Encryption.cs.
import CryptoKit
import Foundation
/// The 32-bit magic number derived from the security key.
///
/// Only its top 16 bits go on the wire (`Framing`), but the whole value is
/// what a peer compares against, so it must be reproduced bit for bit.
public enum MagicHash {
/// Number of times the SHA-512 digest is re-hashed after the first pass
/// (`Encryption.cs:192`); 50 001 digests in total.
private static let rehashRounds = 50_000
/// `Get24BitHash(key)` (`Encryption.cs:173-200`).
///
/// The key is written into a fixed 32-byte zero buffer, one byte per
/// UTF-16 code unit **truncated to eight bits** (`Encryption.cs:185`), so
/// a non-ASCII key hashes to whatever the low bytes of its code units are —
/// matching Windows rather than being correct.
public static func magicNumber(for key: String) -> UInt32 {
guard !key.isEmpty else { return 0 } // Encryption.cs:175-178
var buffer = [UInt8](repeating: 0, count: packageSize) // Encryption.cs:180
for (i, unit) in key.utf16.enumerated() {
guard i < packageSize else { break } // Encryption.cs:181-183
buffer[i] = UInt8(truncatingIfNeeded: unit)
}
var digest = [UInt8](SHA512.hash(data: buffer))
for _ in 0..<rehashRounds {
digest = [UInt8](SHA512.hash(data: digest))
}
// Encryption.cs:199. `hashValue[0] << 23`, not << 24: the first two
// terms overlap at bit 23 and the sum carries. The C# expression is
// `int` arithmetic in an unchecked context and does overflow, so the
// additions wrap; `&+` on UInt32 gives the same 32 bits.
let high = UInt32(digest[0]) << 23
let mid = UInt32(digest[1]) << 16
let last = UInt32(digest[digest.count - 1]) << 8 // hashValue[^1], i.e. byte 63
return high &+ mid &+ last &+ UInt32(digest[2])
}
}
/// The rules the security key itself has to follow: length, generation and
/// the grouped form shown to the user (`Encryption.cs:65-79, 202-242`).
public enum SecurityKey {
/// Minimum key length in characters (`Encryption.cs:237`, `PW_LENGTH`
/// at `Encryption.cs:207`).
public static let minimumLength = 16
/// The four character sets a generated key draws from, in order
/// (`Encryption.cs:212`). `"` `'` `` ` `` `O` `0` and `&` are left out
/// because they confuse users.
private static let charsets = [
"abcdefghjkmnpqrstuvxyz",
"ABCDEFGHJKMNPQRSTUVXYZ",
"123456789",
"~!@#$%^*()_-+=:;<,>.?/\\|[]",
]
/// Whether a key may be used; validation is length-only, as on Windows
/// (`Encryption.cs:235-242`). There is no weak-key or charset check there
/// and adding one here would reject keys a Windows peer accepts.
public static func isValid(_ key: String) -> Bool {
key.count >= minimumLength
}
/// A key as typed by the user, with all whitespace discarded
/// (`Form/Settings/SetupPage2a.cs:92`) — the same normalisation that makes
/// the grouped `displayText` form safe to copy between machines.
public static func normalize(_ typed: String) -> String {
typed.filter { !$0.isWhitespace }
}
/// A fresh 16-character key, one character taken round-robin from each of
/// the four sets (`Encryption.cs:209-233`).
///
/// Windows takes a random byte and reduces it modulo the set size, which is
/// slightly biased; `randomElement()` over `SystemRandomNumberGenerator` is
/// not, and nothing on the wire depends on how the key was chosen.
public static func random() -> String {
var key = ""
while key.count < minimumLength {
for set in charsets {
guard let c = set.randomElement() else { continue }
key.append(c)
if key.count >= minimumLength { break } // Encryption.cs:224-227
}
}
return key
}
/// The key in groups of four separated by two spaces, as the Windows UI
/// shows it (`KeyDisplayedText`, `Encryption.cs:65-79`). `normalize`
/// reverses it.
public static func displayText(_ key: String) -> String {
let chars = Array(key)
var out = ""
var i = 0
repeat {
let end = min(i + 4, chars.count)
out += String(chars[i..<end]) + " "
i += 4
} while i < chars.count - 1 // Encryption.cs:76
return out.trimmingCharacters(in: .whitespaces)
}
}
+404
View File
@@ -0,0 +1,404 @@
// The `DATA` packet of the Mouse Without Borders wire protocol: its type
// numbering, its size rule and the overlapping field views over one
// little-endian byte buffer. See docs/protocol.md §1.1-§1.2.
//
// Ported from App/Core/DATA.cs, App/Core/Package.cs, App/Core/PackageType.cs,
// App/Core/MOUSEDATA.cs, App/Core/KEYBDDATA.cs, App/Core/ID.cs.
import Foundation
/// Size in bytes of a small packet (`Package.PACKAGE_SIZE`, `Package.cs:17`).
public let packageSize = 32
/// Size in bytes of a big packet (`Package.PACKAGE_SIZE_EX`, `Package.cs:18`).
public let packageSizeEx = 64
/// What a packet is for; one byte on the wire (`PackageType.cs:15-57`).
///
/// Values the Windows build does not define decode as `.unknown` rather than
/// failing, so a newer peer cannot desynchronise our framing: the size rule
/// below is enough to keep the stream aligned.
public enum PackageType: RawRepresentable, Sendable, Hashable {
case hi // 2, PackageType.cs:22
case hello // 3, PackageType.cs:23
case byeBye // 4, PackageType.cs:24
case heartbeat // 20, PackageType.cs:26
case awake // 21, PackageType.cs:27
case hideMouse // 50, PackageType.cs:28
case heartbeatEx // 51, PackageType.cs:29
case heartbeatExL2 // 52, PackageType.cs:30
case heartbeatExL3 // 53, PackageType.cs:31
case clipboard // 69, PackageType.cs:33
case clipboardDragDrop // 70, PackageType.cs:34
case clipboardDragDropEnd // 71, PackageType.cs:35
case explorerDragDrop // 72, PackageType.cs:36
case clipboardCapture // 73, PackageType.cs:37
case captureScreenCommand // 74, PackageType.cs:38
case clipboardDragDropOperation // 75, PackageType.cs:39
case clipboardDataEnd // 76, PackageType.cs:40
case machineSwitched // 77, PackageType.cs:41
case clipboardAsk // 78, PackageType.cs:42
case clipboardPush // 79, PackageType.cs:43
case nextMachine // 121, PackageType.cs:45
case keyboard // 122, PackageType.cs:46
case mouse // 123, PackageType.cs:47
case clipboardText // 124, PackageType.cs:48
case clipboardImage // 125, PackageType.cs:49
case handshake // 126, PackageType.cs:51
case handshakeAck // 127, PackageType.cs:52
case matrix // 128 = 0x80, PackageType.cs:54; the flags below are OR'd in
case error // 0xFE, PackageType.cs:20 — never on the wire, a 0-byte read
case invalid // 0xFF, PackageType.cs:18 — never on the wire, bad framing
/// Any other byte value, kept verbatim so it can be re-encoded and sized.
case unknown(UInt8)
/// Bit 0x80: set on every `Matrix` packet (`DATA.cs:131`).
public static let matrixBit: UInt8 = 128
/// OR'd into a `Matrix` type when the two machines are swapping slots
/// (`MatrixSwapFlag = 2`, `PackageType.cs:55`).
public static let matrixSwapFlag: UInt8 = 2
/// OR'd into a `Matrix` type when the matrix is two rows
/// (`MatrixTwoRowFlag = 4`, `PackageType.cs:56`).
public static let matrixTwoRowFlag: UInt8 = 4
/// The byte that goes at offset 0 (`DATA.cs:27-28`).
public var rawValue: UInt8 {
switch self {
case .hi: return 2
case .hello: return 3
case .byeBye: return 4
case .heartbeat: return 20
case .awake: return 21
case .hideMouse: return 50
case .heartbeatEx: return 51
case .heartbeatExL2: return 52
case .heartbeatExL3: return 53
case .clipboard: return 69
case .clipboardDragDrop: return 70
case .clipboardDragDropEnd: return 71
case .explorerDragDrop: return 72
case .clipboardCapture: return 73
case .captureScreenCommand: return 74
case .clipboardDragDropOperation: return 75
case .clipboardDataEnd: return 76
case .machineSwitched: return 77
case .clipboardAsk: return 78
case .clipboardPush: return 79
case .nextMachine: return 121
case .keyboard: return 122
case .mouse: return 123
case .clipboardText: return 124
case .clipboardImage: return 125
case .handshake: return 126
case .handshakeAck: return 127
case .matrix: return PackageType.matrixBit
case .error: return 0xFE
case .invalid: return 0xFF
case .unknown(let raw): return raw
}
}
/// Never fails: an unrecognised byte becomes `.unknown`.
public init(rawValue: UInt8) {
switch rawValue {
case 2: self = .hi
case 3: self = .hello
case 4: self = .byeBye
case 20: self = .heartbeat
case 21: self = .awake
case 50: self = .hideMouse
case 51: self = .heartbeatEx
case 52: self = .heartbeatExL2
case 53: self = .heartbeatExL3
case 69: self = .clipboard
case 70: self = .clipboardDragDrop
case 71: self = .clipboardDragDropEnd
case 72: self = .explorerDragDrop
case 73: self = .clipboardCapture
case 74: self = .captureScreenCommand
case 75: self = .clipboardDragDropOperation
case 76: self = .clipboardDataEnd
case 77: self = .machineSwitched
case 78: self = .clipboardAsk
case 79: self = .clipboardPush
case 121: self = .nextMachine
case 122: self = .keyboard
case 123: self = .mouse
case 124: self = .clipboardText
case 125: self = .clipboardImage
case 126: self = .handshake
case 127: self = .handshakeAck
case PackageType.matrixBit: self = .matrix
case 0xFE: self = .error
case 0xFF: self = .invalid
default: self = .unknown(rawValue)
}
}
/// True when the packet is 64 bytes and therefore carries a machine name.
///
/// `DATA.cs:124-133`: a fixed list of types, **or** any type with the
/// `Matrix` bit set. Note the consequence the Windows receive loop relies
/// on (`SocketStuff.cs:558-610`): `Error` (0xFE) and `Invalid` (0xFF) also
/// have that bit, so a packet rejected by framing still consumes 64 bytes.
public var isBig: Bool {
switch self {
case .hello, .awake, .heartbeat, .heartbeatEx, .handshake, .handshakeAck,
.clipboardPush, .clipboard, .clipboardAsk, .clipboardImage, .clipboardText,
.clipboardDataEnd:
return true
default:
return (rawValue & PackageType.matrixBit) != 0
}
}
/// True for a `Matrix` packet, with or without the swap/two-row flags
/// (`DATA.cs:131`).
public var isMatrix: Bool { (rawValue & PackageType.matrixBit) != 0 }
/// Size on the wire in bytes.
public var packetSize: Int { isBig ? packageSizeEx : packageSize }
}
/// A machine id (`ID`, `ID.cs:15-19`); `Src` and `Des` on the wire.
public enum MachineID {
/// No machine (`ID.NONE`, `ID.cs:17`).
public static let none: UInt32 = 0
/// Broadcast to every machine (`ID.ALL`, `ID.cs:18`).
public static let all: UInt32 = 255
}
/// The mouse view of bytes 16..31 (`MOUSEDATA`, `MOUSEDATA.cs:18-26`).
public struct MouseData: Sendable, Hashable {
/// X coordinate, normalised per docs/protocol.md §4.4.
public var x: Int32
/// Y coordinate, normalised per docs/protocol.md §4.4.
public var y: Int32
/// Wheel delta in Windows units (120 per notch); also carries an id in
/// `NextMachine` packets.
public var wheelDelta: Int32
/// `MOUSEEVENTF_*` flags.
public var flags: Int32
/// A mouse view with the given fields.
public init(x: Int32 = 0, y: Int32 = 0, wheelDelta: Int32 = 0, flags: Int32 = 0) {
self.x = x
self.y = y
self.wheelDelta = wheelDelta
self.flags = flags
}
}
/// The keyboard view of bytes 16..31: `DateTime` then `KEYBDDATA`
/// (`DATA.cs:39-43`, `KEYBDDATA.cs:18-25`).
public struct KeyboardData: Sendable, Hashable {
/// Send timestamp, set only for `Keyboard` packets (`Event.cs:266`) and
/// ignored on receive.
public var dateTime: Int64
/// Windows virtual-key code (`wVk`).
public var virtualKey: Int32
/// `KEYEVENTF_*` / `LLKHF_*` flags (`dwFlags`).
public var flags: Int32
/// A keyboard view with the given fields.
public init(dateTime: Int64 = 0, virtualKey: Int32 = 0, flags: Int32 = 0) {
self.dateTime = dateTime
self.virtualKey = virtualKey
self.flags = flags
}
}
/// Why a machine name could not be put into a packet.
public enum PacketError: Error, Sendable, Hashable {
/// The name contains a character outside 7-bit ASCII, which cannot survive
/// the Windows `ASCIIEncoding` round trip (`Common.cs:397-405`).
case machineNameNotASCII
/// The name is longer than the 32-byte field (`DATA.cs:86-93`).
case machineNameTooLong
}
/// One protocol packet: a 64-byte little-endian buffer with overlapping field
/// views, of which the first 32 or all 64 bytes go on the wire.
///
/// Mirrors `DATA` (`DATA.cs:24-149`), which is an explicit-layout struct
/// marshalled with `Marshal.StructureToPtr` — little-endian, natural
/// alignment, no padding. Storage is always 64 bytes, as `DATA` always is;
/// `bytes` truncates to 32 for a small packet exactly as `DATA.Bytes` does
/// (`DATA.cs:105-113`).
public struct Packet: Sendable, Hashable {
private var buffer: [UInt8]
/// A zeroed packet of the given type.
public init(type: PackageType) {
buffer = [UInt8](repeating: 0, count: packageSizeEx)
self.type = type
}
/// A packet over received bytes, without any framing check; `nil` unless
/// there are exactly 32 or 64 of them.
///
/// A 32-byte buffer is zero-extended to 64, as `DATA.Bytes` does
/// (`DATA.cs:115-121`).
public init?(bytes: Data) {
guard bytes.count == packageSize || bytes.count == packageSizeEx else { return nil }
var buf = [UInt8](repeating: 0, count: packageSizeEx)
buf.replaceSubrange(0..<bytes.count, with: bytes)
buffer = buf
}
/// The wire bytes: 32 for a small packet, 64 for a big one
/// (`DATA.cs:105-113`).
public var bytes: Data { Data(buffer[0..<type.packetSize]) }
/// Package type, byte 0 (`DATA.cs:27-28`). Only byte 0 survives the wire:
/// bytes 1..3 are the checksum and magic (`Framing`).
public var type: PackageType {
get { PackageType(rawValue: buffer[0]) }
set { buffer[0] = newValue.rawValue }
}
/// Packet sequence number, offset 4 (`DATA.cs:30-31`).
public var id: Int32 {
get { loadInt32(4) }
set { store(UInt32(bitPattern: newValue), at: 4) }
}
/// Source machine id, offset 8 (`DATA.cs:33-34`). In `Matrix` packets this
/// is a 1-based slot index instead (docs/protocol.md §4.2).
public var src: UInt32 {
get { loadUInt32(8) }
set { store(newValue, at: 8) }
}
/// Destination machine id, offset 12 (`DATA.cs:36-37`); `MachineID.all`
/// broadcasts.
public var des: UInt32 {
get { loadUInt32(12) }
set { store(newValue, at: 12) }
}
/// The mouse view of bytes 16..31 (`DATA.cs:45-46`).
public var mouse: MouseData {
get {
MouseData(
x: loadInt32(16), y: loadInt32(20), wheelDelta: loadInt32(24),
flags: loadInt32(28))
}
set {
store(UInt32(bitPattern: newValue.x), at: 16)
store(UInt32(bitPattern: newValue.y), at: 20)
store(UInt32(bitPattern: newValue.wheelDelta), at: 24)
store(UInt32(bitPattern: newValue.flags), at: 28)
}
}
/// The keyboard view of bytes 16..31 (`DATA.cs:39-43`).
public var keyboard: KeyboardData {
get {
KeyboardData(
dateTime: Int64(bitPattern: loadUInt64(16)), virtualKey: loadInt32(24),
flags: loadInt32(28))
}
set {
store(UInt64(bitPattern: newValue.dateTime), at: 16)
store(UInt32(bitPattern: newValue.virtualKey), at: 24)
store(UInt32(bitPattern: newValue.flags), at: 28)
}
}
/// The handshake nonce view of bytes 16..31: `Machine1..4`
/// (`DATA.cs:48-58`).
public var nonce: (UInt32, UInt32, UInt32, UInt32) {
get { (loadUInt32(16), loadUInt32(20), loadUInt32(24), loadUInt32(28)) }
set {
store(newValue.0, at: 16)
store(newValue.1, at: 20)
store(newValue.2, at: 24)
store(newValue.3, at: 28)
}
}
/// The clipboard post-action view of bytes 16..19 (`DATA.cs:60-61`;
/// `ClipboardPostAction.cs:20-25`: Other 0, Desktop 1, Mspaint 2).
public var postAction: UInt32 {
get { loadUInt32(16) }
set { store(newValue, at: 16) }
}
/// Bytes 16..63, the 48-byte clipboard chunk of a big packet
/// (`Clipboard.cs:46, 274`: `dataStart = PACKAGE_SIZE_EX - DATA_SIZE`).
/// Writing fewer than 48 bytes zero-fills the rest, as the Windows sender
/// does for the last chunk (`Clipboard.cs:281`).
public var payload48: Data {
get { Data(buffer[16..<packageSizeEx]) }
set {
var chunk = [UInt8](repeating: 0, count: Packet.clipboardChunkSize)
let n = min(newValue.count, Packet.clipboardChunkSize)
chunk.replaceSubrange(0..<n, with: newValue.prefix(n))
buffer.replaceSubrange(16..<packageSizeEx, with: chunk)
}
}
/// Bytes of the clipboard chunk carried by one big packet
/// (`DATA_SIZE = 48`, `Clipboard.cs:46`).
public static let clipboardChunkSize = 48
/// The sender's machine name from bytes 32..63, or `nil` on a small packet
/// that has no such field (`DATA.cs:63-94`).
///
/// Decoded as ASCII like `Common.GetString` (`Common.cs:402-405`), which
/// substitutes `?` for any byte above 0x7F, then trimmed as `DATA.cs:83`
/// does. NULs are trimmed too, which `String.Trim()` does not do, so that a
/// zero-filled field reads as empty rather than as 32 NULs.
public var machineName: String? {
guard type.isBig else { return nil }
let ascii = buffer[32..<packageSizeEx].map { $0 < 0x80 ? Character(UnicodeScalar($0)) : "?" }
return String(ascii).trimmingCharacters(in: machineNameTrimSet)
}
/// Writes bytes 32..63 with `name`, right-padded with spaces to 32 bytes
/// (`DATA.cs:86-93`).
///
/// Not a property setter because a non-ASCII name is rejected rather than
/// silently turned into `?`: Windows would encode it lossily
/// (`Common.cs:397-400`) and the peer could never resolve the machine.
public mutating func setMachineName(_ name: String) throws {
guard name.allSatisfy({ $0.isASCII }) else { throw PacketError.machineNameNotASCII }
guard name.utf8.count <= 32 else { throw PacketError.machineNameTooLong }
var field = [UInt8](repeating: 0x20, count: 32) // PadRight(32, ' '), DATA.cs:88
field.replaceSubrange(0..<name.utf8.count, with: Array(name.utf8))
buffer.replaceSubrange(32..<packageSizeEx, with: field)
}
// MARK: - Little-endian access
private func loadUInt32(_ offset: Int) -> UInt32 {
UInt32(buffer[offset]) | (UInt32(buffer[offset + 1]) << 8)
| (UInt32(buffer[offset + 2]) << 16) | (UInt32(buffer[offset + 3]) << 24)
}
private func loadInt32(_ offset: Int) -> Int32 { Int32(bitPattern: loadUInt32(offset)) }
private func loadUInt64(_ offset: Int) -> UInt64 {
UInt64(loadUInt32(offset)) | (UInt64(loadUInt32(offset + 4)) << 32)
}
private mutating func store(_ value: UInt32, at offset: Int) {
buffer[offset] = UInt8(truncatingIfNeeded: value)
buffer[offset + 1] = UInt8(truncatingIfNeeded: value >> 8)
buffer[offset + 2] = UInt8(truncatingIfNeeded: value >> 16)
buffer[offset + 3] = UInt8(truncatingIfNeeded: value >> 24)
}
private mutating func store(_ value: UInt64, at offset: Int) {
store(UInt32(truncatingIfNeeded: value), at: offset)
store(UInt32(truncatingIfNeeded: value >> 32), at: offset + 4)
}
}
/// Characters stripped from both ends of a decoded machine name: the space
/// Windows pads with (`DATA.cs:88`) plus NUL from a zero-filled field.
private let machineNameTrimSet = CharacterSet.whitespacesAndNewlines.union(
CharacterSet(charactersIn: "\0"))
+7 -7
View File
@@ -18,21 +18,21 @@ ones in §Out of scope.
## 1. wire-core (core) — `Sources/MWBCore/Packet.swift`, `Framing.swift`, `MagicHash.swift`, `CipherStream.swift` ## 1. wire-core (core) — `Sources/MWBCore/Packet.swift`, `Framing.swift`, `MagicHash.swift`, `CipherStream.swift`
- [ ] `PackageType` (raw `UInt8`, every value §1.2), big/small rule §1.1, - [x] `PackageType` (raw `UInt8`, every value §1.2), big/small rule §1.1,
unknown values tolerated. unknown values tolerated.
- [ ] `Packet` over a 32/64-byte little-endian buffer with union views: - [x] `Packet` over a 32/64-byte little-endian buffer with union views:
mouse, keyboard, nonce, postAction, machineName, 48-byte clipboard mouse, keyboard, nonce, postAction, machineName, 48-byte clipboard
payload at offset 16. payload at offset 16.
- [ ] ASCII space-padded 32-byte machine name; non-ASCII refused. - [x] ASCII space-padded 32-byte machine name; non-ASCII refused.
- [ ] `Framing.seal` / `open` exactly §1.3 (checksum bytes 2..31, magic - [x] `Framing.seal` / `open` exactly §1.3 (checksum bytes 2..31, magic
top 16 bits, bytes 1–3 zeroed on open). top 16 bits, bytes 1–3 zeroed on open).
- [ ] `magicNumber(for:)` §2.1 (50 001 SHA-512 rounds, `<< 23` overlap, - [x] `magicNumber(for:)` §2.1 (50 001 SHA-512 rounds, `<< 23` overlap,
UTF-16 unit truncated to a byte, 32-byte buffer). UTF-16 unit truncated to a byte, 32-byte buffer).
- [ ] PBKDF2-HMAC-SHA512 100 000 rounds / 32 bytes via CommonCrypto; - [x] PBKDF2-HMAC-SHA512 100 000 rounds / 32 bytes via CommonCrypto;
`CipherWriter` / `CipherReader` with 16+16 header, sacrificial `CipherWriter` / `CipherReader` with 16+16 header, sacrificial
block, streaming AES-256-CBC no padding §2.3. No secrets in block, streaming AES-256-CBC no padding §2.3. No secrets in
descriptions or logs. descriptions or logs.
- [ ] Key rules §2.4: 16-char minimum, generator with the four charsets, - [x] Key rules §2.4: 16-char minimum, generator with the four charsets,
display grouping. display grouping.
## 2. session-matrix (core) — `Sources/MWBCore/Session.swift`, `Matrix.swift`, `MachinePool.swift`, `Edge.swift`, `Coordinates.swift` ## 2. session-matrix (core) — `Sources/MWBCore/Session.swift`, `Matrix.swift`, `MachinePool.swift`, `Edge.swift`, `Coordinates.swift`
+301 -28
View File
@@ -25,7 +25,14 @@ Windows build is the whole point (CLAUDE.md invariant 1).
the name half. Say so in a comment at the loop. the name half. Say so in a comment at the loop.
- **Unknown type values decode as `.unknown(UInt8)`**, not an error, so - **Unknown type values decode as `.unknown(UInt8)`**, not an error, so
a newer Windows build cannot desynchronise framing; their size follows a newer Windows build cannot desynchronise framing; their size follows
the `0x80` rule. the `0x80` rule. Type `0` is included: Windows throws there
(`DATA.cs:126-127`), we decode a small `.unknown(0)` rather than fail a
receive loop over a byte that is not a legal type anyway.
- **`Error` (0xFE) and `Invalid` (0xFF) are big packets**, because they
carry the `0x80` bit. This is not a quirk we chose: the Windows receive
loop reads 32 more bytes after rejecting a packet
(`SocketStuff.cs:578-600`), and a receiver that does not will
desynchronise. See protocol §10.1 note 1.
- **Machine names are ASCII, ≤ 32, space-padded** (`Common.cs:397-405`, - **Machine names are ASCII, ≤ 32, space-padded** (`Common.cs:397-405`,
`DATA.cs:75-94`); non-ASCII is a construction error; decode trims `DATA.cs:75-94`); non-ASCII is a construction error; decode trims
trailing spaces and NULs. trailing spaces and NULs.
@@ -40,9 +47,18 @@ Windows build is the whole point (CLAUDE.md invariant 1).
fixed 32-byte buffer (`Encryption.cs:180-186`); the `<< 23` overlap fixed 32-byte buffer (`Encryption.cs:180-186`); the `<< 23` overlap
is reproduced with `UInt32` wrapping arithmetic in the C# order. is reproduced with `UInt32` wrapping arithmetic in the C# order.
- **Salt and IV are fresh per direction**; the sacrificial block is - **Salt and IV are fresh per direction**; the sacrificial block is
inside the cipher types' contract: the writer emits it after the inside the cipher types' contract: `CipherWriter.header` is the whole
header, the reader discards the first 16 plaintext bytes 48-byte preamble (salt, IV, then the *encrypted* random block), and
(`Common.cs:1528-1558`). `CipherReader` eats the peer's preamble out of the byte stream and
discards the first 16 plaintext bytes (`Common.cs:1528-1558`,
`SocketStuff.cs:105, 119`).
- **Randomness comes from `SystemRandomNumberGenerator`**, documented as
cryptographically secure on Apple platforms — the salt, the IV and the
sacrificial block all come from it, matching
`RandomNumberGenerator.Fill` (`Encryption.cs:125`). Generated keys use
it too, via unbiased `randomElement()` rather than the Windows modulo
reduction (`Encryption.cs:222`); nothing on the wire depends on how a
key was chosen.
- **A wrong key is not detectable here** (no MAC). The reader returns - **A wrong key is not detectable here** (no MAC). The reader returns
garbage and framing rejects it, matching Windows (`InvalidKey` after garbage and framing rejects it, matching Windows (`InvalidKey` after
more than 10 bad packets). more than 10 bad packets).
@@ -51,32 +67,106 @@ Windows build is the whole point (CLAUDE.md invariant 1).
### Promised (topo.md handshakes 1 and 2, to session-matrix, control-channel, clipboard) ### Promised (topo.md handshakes 1 and 2, to session-matrix, control-channel, clipboard)
As shipped 2026-09-16. Later lanes code against this.
```swift ```swift
public enum PackageType: RawRepresentable, Sendable { case hi, hello, …, unknown(UInt8); var rawValue: UInt8; var isBig: Bool } public let packageSize = 32 // Package.cs:17
public struct Packet: Sendable { public let packageSizeEx = 64 // Package.cs:18
public var type: PackageType; public var id: Int32; public var src: UInt32; public var des: UInt32
public var mouse: MouseData // x, y, wheelDelta, flags at 16..31 public enum PackageType: RawRepresentable, Sendable, Hashable {
public var keyboard: KeyboardData // dateTime at 16, vk at 24, flags at 28 case hi, hello, byeBye, heartbeat, awake, hideMouse, heartbeatEx, heartbeatExL2,
public var nonce: (UInt32, UInt32, UInt32, UInt32) heartbeatExL3, clipboard, clipboardDragDrop, clipboardDragDropEnd, explorerDragDrop,
public var postAction: UInt32 clipboardCapture, captureScreenCommand, clipboardDragDropOperation, clipboardDataEnd,
public var machineName: String? // nil on small packets machineSwitched, clipboardAsk, clipboardPush, nextMachine, keyboard, mouse,
public var payload48: Data // bytes 16..63 for clipboard chunks clipboardText, clipboardImage, handshake, handshakeAck, matrix, error, invalid
public init(type:) // zeroed buffer of the right size case unknown(UInt8)
public init?(bytes: Data) // 32 or 64 bytes, no framing check public init(rawValue: UInt8) // never fails
public var bytes: Data // 32 or 64 public var rawValue: UInt8
public var isBig: Bool // true for .error and .invalid too — see below
public var isMatrix: Bool
public var packetSize: Int // 32 or 64
public static let matrixBit: UInt8 // 0x80
public static let matrixSwapFlag: UInt8 // 2
public static let matrixTwoRowFlag: UInt8 // 4
} }
public enum MachineID { public static let none: UInt32; public static let all: UInt32 }
public struct MouseData: Sendable, Hashable { public var x, y, wheelDelta, flags: Int32 }
public struct KeyboardData: Sendable, Hashable {
public var dateTime: Int64; public var virtualKey, flags: Int32
}
public enum PacketError: Error { case machineNameNotASCII, machineNameTooLong }
public struct Packet: Sendable, Hashable {
public init(type: PackageType)
public init?(bytes: Data) // 32 or 64 bytes, no framing check
public var bytes: Data // 32 or 64
public var type: PackageType
public var id: Int32
public var src: UInt32
public var des: UInt32
public var mouse: MouseData // bytes 16..31
public var keyboard: KeyboardData // dateTime 16, vk 24, flags 28
public var nonce: (UInt32, UInt32, UInt32, UInt32) // bytes 16..31
public var postAction: UInt32 // bytes 16..19
public var payload48: Data // bytes 16..63, zero-filled when short
public var machineName: String? { get } // nil on small packets
public mutating func setMachineName(_ name: String) throws
public static let clipboardChunkSize = 48
}
public enum Framing { public enum Framing {
public static func seal(_ p: Packet, magic: UInt32) -> Data public static func seal(_ packet: Packet, magic: UInt32) -> Data
public static func open(_ bytes: Data, magic: UInt32) -> Packet // .invalid on bad framing public static func open(_ bytes: Data, magic: UInt32) -> Packet // .invalid on bad framing
} }
public enum MagicHash { public static func magicNumber(for key: String) -> UInt32 } public enum MagicHash { public static func magicNumber(for key: String) -> UInt32 }
public enum SecurityKey { public static func isValid(_:) -> Bool; public static func random() -> String; public static func displayText(_:) -> String }
public struct CipherWriter { public init(key: String) throws; public mutating func header() -> Data; public mutating func write(_ plaintext: Data) throws -> Data } public enum SecurityKey {
public struct CipherReader { public init(key: String); public mutating func read(_ ciphertext: Data) throws -> Data } public static let minimumLength = 16
public static func isValid(_ key: String) -> Bool
public static func normalize(_ typed: String) -> String // discards whitespace
public static func random() -> String
public static func displayText(_ key: String) -> String
}
public enum CipherError: Error {
case keyDerivationFailed, cryptorCreationFailed(Int32), cryptorUpdateFailed(Int32)
}
public final class CipherWriter {
public init(securityKey: String) throws
public let header: Data // 48 bytes: salt | IV | encrypted sacrificial block
public func write(_ plaintext: Data) throws -> Data
}
public final class CipherReader {
public init(securityKey: String)
public func read(_ ciphertext: Data) throws -> Data // eats the peer preamble itself
}
``` ```
Exact spelling may change during the lane; this README is updated in Three deviations from the shape proposed at planning time, all deliberate:
the same change and later lanes code against it.
- **`machineName` is a read-only property plus `setMachineName(_:) throws`.**
A setter cannot reject a non-ASCII name, and silently encoding one as `?`
the way Windows does would produce a machine nobody can resolve.
- **`CipherWriter` / `CipherReader` are `final class`, not `struct`.** They own
CBC chaining state in a `CCCryptorRef`; a struct copy would fork one stream
into two that each think they own the chain. They are **not `Sendable`**:
one connection owns one of each, on one queue.
- **`CipherWriter.header` is a stored `let`, not a `mutating func`,** and it
includes the encrypted sacrificial block, so it is 48 bytes. Write it
verbatim before the first packet; there is nothing else to remember.
Two rules the consuming lanes must honour:
- **`Framing.open` returning `.invalid` still means 64 bytes on the wire**
(protocol §10.1 note 1). Receive loop: read 32, `Framing.open`, and if
`packet.type.isBig`, read 32 more and `Framing.open` the concatenated 64 —
the checksum covers bytes 2..31 either way, so opening twice is identical to
what Windows does.
- **Nothing may be acted on before `Framing.open` returns a non-`.invalid`
packet** (CLAUDE.md invariant 2). There is no MAC: framing under the
key-derived magic number is the only authentication in this protocol.
### Consumed ### Consumed
@@ -84,21 +174,204 @@ the same change and later lanes code against it.
## Status / TODO ## Status / TODO
- [ ] `Sources/MWBCore/Packet.swift`: `PackageType` (every value §1.2, - [x] `Sources/MWBCore/Packet.swift`: `PackageType` (every value §1.2,
cited), `isBig`, `Packet` with union views, machine name rules. cited), `isBig`, `Packet` with union views, machine name rules.
- [ ] `Sources/MWBCore/Framing.swift`: `seal` / `open` per §1.3, each - [x] `Sources/MWBCore/Framing.swift`: `seal` / `open` per §1.3, each
constant cited to `SocketStuff.cs`. constant cited to `SocketStuff.cs`.
- [ ] `Sources/MWBCore/MagicHash.swift`: `magicNumber(for:)` §2.1 cited - [x] `Sources/MWBCore/MagicHash.swift`: `magicNumber(for:)` §2.1 cited
to `Encryption.cs:173-200`; `SecurityKey` rules §2.4 to `Encryption.cs:173-200`; `SecurityKey` rules §2.4
(`Encryption.cs:207-242`, `:65-79`). (`Encryption.cs:207-242`, `:65-79`).
- [ ] `Sources/MWBCore/CipherStream.swift`: PBKDF2, `CipherWriter`, - [x] `Sources/MWBCore/CipherStream.swift`: PBKDF2, `CipherWriter`,
`CipherReader` (header, sacrificial block, streaming CBC), cited to `CipherReader` (header, sacrificial block, streaming CBC), cited to
`Encryption.cs` and `Common.cs:1528-1558`; the CommonCrypto wrapper `Encryption.cs` and `Common.cs:1528-1558`; the CommonCrypto wrapper
lives in this one file. lives in this one file.
- [ ] `docs/protocol.md`: add anything learned while porting, cited. - [x] `docs/protocol.md`: add anything learned while porting, cited.
## Work log ## Work log
### 2026-09-16 — dev (Opus)
Ported all four files; `tools/gates.sh` green. What each file is
responsible for, in one sentence apiece:
- `Packet.swift` (404 lines) — the `DATA` buffer and its overlapping
field views. Storage is always 64 bytes, as `DATA` always is, and
`bytes` truncates to 32 for a small packet exactly as `DATA.Bytes`
does (`DATA.cs:105-113`); that removed all resize logic from the type
setter and made the union views trivial offset reads. `PackageType` is
a `RawRepresentable` enum with a non-failable `init(rawValue:)` (Swift
accepts one where a failable initialiser is required), so an
unrecognised byte round-trips as `.unknown(raw)` and still sizes
correctly.
- `Framing.swift` (72 lines) — bytes 1..3 only: the 8-bit sum of bytes
2..31 and the magic's top 16 bits.
- `MagicHash.swift` (113 lines) — everything derived from the key
string: its magic number, and its validity/generation/display rules.
Two responsibilities by the letter of the one-sentence test, one by
its spirit: both are "what the key string means", neither is 30 lines,
and splitting would give the next reader two files to find.
- `CipherStream.swift` (212 lines) — the per-direction CBC stream and
the only CommonCrypto in the project. `CCCryptorUpdate` already buffers
a partial block internally, so the only buffering written by hand is
the reader's 32 cleartext preamble bytes.
Key decisions and deviations:
1. **`CipherWriter`/`CipherReader` are classes, `machineName` is set
through a throwing method, and `header` is a stored property.**
Reasons and the exact signatures are in Handshakes above; later lanes
code against that block, not against the planning sketch.
2. **The magic hash needs wrapping arithmetic.** The C# expression
overflows `int` for large digest bytes and is reinterpreted by a
`(uint)` cast; `&+` reproduces it, plain `+` would trap in Swift.
Written up as protocol §10.1 note 3.
3. **`Error`/`Invalid` are big packets.** Found while porting
`IsBigPackage`; it changes how control-channel must frame its reads,
so it is called out in Handshakes and protocol §10.1 note 1.
4. **NULs are trimmed from a decoded machine name**, which `String.Trim`
does not do. Windows pads with spaces, so this cannot change what a
real packet decodes to; it only stops a zero-filled field reading as
32 NULs.
5. **Generated keys use unbiased random selection** instead of the
Windows `% set.Length`. Local-only choice, noted in Assumptions.
Verified by hand (no test suite, per CLAUDE.md — the user tests the
app). Each check was run from a throwaway `swiftc` build of `MWBCore`
in the scratchpad, against an *independent* implementation, never
against our own encoder:
- Magic number for `abcdefghijklmnop` = `334517251`, matching a Python
SHA-512 chain of the same 50 001 rounds.
- PBKDF2-HMAC-SHA512 (100 000 rounds, salt 16×0x01) matching Python's
`hashlib.pbkdf2_hmac`.
- `CipherReader` fed a 112-byte stream built by `openssl enc
-aes-256-cbc -nopad` from that derived key — delivered in 13-byte
slices to exercise the preamble and partial-block buffering — returns
exactly the 64 plaintext packet bytes, and `Framing.open` then reads
it back as `handshake` / `MACBOOK`.
- Packet offsets, the 32/64 size rule, seal→open round trip, and
rejection of a flipped payload byte, a wrong magic and a short buffer.
No macOS permission was requested, no event was posted, no pasteboard
was touched.
## QA log ## QA log
### 2026-09-16 — QA (Sonnet)
Ran `tools/guard.sh -t 600 -- tools/gates.sh`: all three gates green
(`swift-format lint --strict`, MWBCore layering, `swift build
-Xswiftc -warnings-as-errors`).
Checked every Status/TODO tick against the code and, line by line,
against the Windows source at
`/Users/guoliangchen/repo/PowerToys/src/modules/MouseWithoutBorders/App/`:
- `PackageType` raw values — every one of the 26 named types plus
`Matrix`/`Error`/`Invalid` compared 1:1 against `PackageType.cs:15-57`.
Exact match, including `MatrixSwapFlag`/`MatrixTwoRowFlag` as static
constants rather than enum cases (they are OR'd flags, not standalone
wire types).
- `isBig`'s explicit 12-type list (`Packet.swift:148-150`) matches
`DATA.cs:130` (`IsBigPackage`) name-for-name and order-for-order; the
bitwise fallback correctly makes `.error` (0xFE) and `.invalid` (0xFF)
big too, reproducing the Windows receive-loop quirk already recorded
in protocol.md §10.1 note 1 — verified by hand against
`SocketStuff.cs:578-600`.
- `Packet` byte offsets — `Type`(0), `Id`(4), `Src`(8), `Des`(12),
`DateTime`/`Md`(16), `Kd`(24), `Machine1..4`(16,20,24,28),
`PostAction`(16), `machineNameP1..4`(32,40,48,56) — checked against
`DATA.cs:27-73` field offsets computed from `sizeof(PackageType) +
n*sizeof(uint)`/`sizeof(long)`. `MOUSEDATA`/`KEYBDDATA` field order
checked against `MOUSEDATA.cs:18-26`, `KEYBDDATA.cs:18-25`. All
correct.
- Checksum range: `Framing.checksum` sums bytes 2..<32 only, matching
`SocketStuff.cs:509-513` (`TcpSendData`) and `:537-543`
(`ProcessReceivedDataEx`), both bounded by `Package.PACKAGE_SIZE`
(32) even though a big packet is 64 bytes on the wire.
- Magic hash: shift amounts and term order (`h[0]<<23, h[1]<<16,
h[last]<<8, h[2]`) match `Encryption.cs:199` exactly, including the
`<<23`/`<<24` overlap. Independently recomputed the documented
example (key `abcdefghijklmnop`) with a fresh Python SHA-512 chain of
50 001 rounds: got decimal `334517251`, matching the doc and the
Swift `&+` wrapping-arithmetic reproduction. **Found the hex gloss
next to that decimal wrong** — `docs/protocol.md:480` said
`0x13EC_4F03`; `334517251` is actually `0x13F0_5403`. Trivial doc typo,
fixed directly (commit `56448cc`, `qa:` prefix); the decimal value and
the Swift code were never wrong.
- PBKDF2: the `CCKeyDerivationPBKDF` call uses `kCCPRFHmacAlgSHA512`,
100 000 rounds, 32-byte output, UTF-8 password — matches
`Encryption.cs:107-115` and `Rfc2898DeriveBytes.Pbkdf2(string, ...)`'s
documented UTF-8 handling. Independently recomputed the documented
vector (key `abcdefghijklmnop`, salt 16×0x01) with Python's
`hashlib.pbkdf2_hmac('sha512', ...)`: got
`6c30ca8b15c27f6e…14ae2a4da14728e1`, matching the doc exactly.
- 48-byte preamble: `CipherWriter.header` is salt(16) + IV(16) +
encrypted sacrificial block(16) = 48 bytes, matching
`Encryption.cs:124-129` (`GetEncryptedStream`) plus
`Common.cs:1528-1558`/`SocketStuff.cs:105,119`
(`SendOrReceiveARandomDataBlockPerInitialIV`, called on the
*encrypted* stream so the sacrificial block is written through the
cipher, not appended in the clear). `CipherReader` consumes the same
32 clear bytes then discards the first 16 *plaintext* bytes the
cryptor emits, matching the Windows reader path
(`SendOrReceiveARandomDataBlockPerInitialIV(decryptedStream, false)`
reads through the already-wrapped `CryptoStream`).
- Big/small rule including `Error`/`Invalid`: covered above under
`isBig`.
Read every changed file top to bottom for readability against CLAUDE.md:
- File sizes: `Packet.swift` 404, `CipherStream.swift` 212,
`MagicHash.swift` 113, `Framing.swift` 72 lines — all well inside the
300–600 target. No function exceeds ~35 lines.
- No `!` force-unwrap, `try!`, `fatalError` or `precondition` anywhere
in the four files (`grep -n '!' ... | grep -v '//' | grep -v '!='`
turns up only `!input.isEmpty`, `!valid`, `!$0.isWhitespace` — boolean
negation, not force-unwrap).
- No `print`/`Logger`/`NSLog` call anywhere in the diff — nothing to
audit for key-material leakage because nothing logs at all.
- `CipherError`/`PacketError` cases carry only status ints or nothing;
none carry key, salt, IV or plaintext, as the doc comment on
`CipherError` promises.
- No dead code, no TODO/FIXME left in the shipped files.
- Every public symbol has a one-line doc comment; comments cite
Windows `file:line` throughout, none cite nothing.
- Confirmed nothing in these four files acts on a packet before
`Framing.open` returns it — they only encode/decode bytes; there is
no packet dispatch here for a "before decrypt" check to apply to
beyond that. The `CipherReader` doc comment correctly states the
invariant for its callers.
One note, not a finding: `SecurityKey.isValid`/`random` measure length
with Swift's `String.count` (grapheme clusters) where Windows measures
`string.Length` (UTF-16 code units) (`Encryption.cs:237`). For the
ASCII character sets the generator and the UI actually produce this
never differs; flagging only so a later lane doesn't assume the two
are interchangeable for arbitrary input.
No macOS permission was requested, no `CGEvent` posted, no pasteboard
was touched, matching CLAUDE.md invariant 5 — this lane has no such
surface to begin with.
Findings: none outstanding (one trivial doc typo found and fixed
directly, see above).
**Verdict: PASS**
## Review ## Review
- 2026-09-16 (lead): inspected per `docs/loop.md` §5. Gates green run
by me; diff touches only the lane's files plus TODO §1, protocol.md
§10.1 and this README. Read all four Swift files: offsets and enum
values match protocol §1, checksum loop is bytes 2..31, magic uses
wrapping adds with the `<< 23` overlap, PBKDF2 parameters and the
48-byte preamble match §2, no logging, no force-unwraps, files 72–404
lines. QA independently recomputed the magic and PBKDF2 vectors.
Verdict: **merge**. Carry into the next brief: (1) `Framing.open` on
an `.invalid` first half still means 64 bytes on the wire — the
control-channel receive loop must read the second half; (2)
`CipherWriter`/`Reader` are non-Sendable classes, so one connection
owns them on one queue; (3) `Packet.setMachineName` throws on
non-ASCII — the app must validate the hostname at startup (D7).
+54
View File
@@ -450,3 +450,57 @@ salt/IV per stream (`EncryptionTests.cs`), received-file staging
**No tests exist for packet layout, framing, handshake, matrix logic, **No tests exist for packet layout, framing, handshake, matrix logic,
coordinate normalization or clipboard chunking** — the port has no coordinate normalization or clipboard chunking** — the port has no
upstream oracle for those and must build its own (`interop-vectors`). upstream oracle for those and must build its own (`interop-vectors`).
---
## 10. Lane notes
Findings a lane made while porting, kept here so the next reader of §1–§9
sees them. One subsection per lane, appended, never rewritten.
### 10.1 wire-core (2026-09-16)
1. **A rejected packet still consumes 64 bytes.** `Error` (0xFE) and
`Invalid` (0xFF) both have the `Matrix` bit 0x80 set, so
`DATA.IsBigPackage` (`DATA.cs:131`) is true for them. The receive loop
builds the `DATA` *after* `ProcessReceivedDataEx` has overwritten byte 0
with 0xFF, then reads 32 more bytes because the packet "is big"
(`SocketStuff.cs:578-600`). A receiver that treats a framing failure as a
32-byte event desynchronises against a real Windows sender that has a
64-byte packet in flight. `PackageType.isBig` reproduces this.
2. **`Type == 0` throws on Windows** (`DATA.cs:126-127`). We decode it as a
small `.unknown(0)` instead: throwing inside a receive path would be a
worse failure than dropping one packet, and 0 is not a legal type.
3. **The magic-number expression overflows `int` and is meant to.**
`(hashValue[0] << 23) + (hashValue[1] << 16) + ...` (`Encryption.cs:199`)
reaches 2 155 806 720 for large digest bytes, past `int.MaxValue`, in C#'s
default unchecked context; it wraps and is then reinterpreted by the
`(uint)` cast. Reproduce with wrapping 32-bit addition — `&+` in Swift, not
`+`, which would trap. **[verified]** against an independent SHA-512
implementation: key `abcdefghijklmnop` ⇒ magic `334517251` (0x13F0_5403).
4. **The stream preamble is 48 bytes, not 32.** 16-byte salt and 16-byte IV in
the clear (`Encryption.cs:124-129`), then one 16-byte *ciphertext* block —
the sacrificial block is random plaintext written *through* the cipher
(`Common.cs:1536-1537` on the stream returned by `GetEncryptedStream`,
wired at `SocketStuff.cs:105, 119`). The reader discards the first 16 bytes
of plaintext, not of ciphertext.
5. **PBKDF2's password is the UTF-8 encoding of the key.** .NET's
`Rfc2898DeriveBytes.Pbkdf2(string, ...)` (`Encryption.cs:109`) documents
UTF-8 for the string overload. **[verified]** against an independent
PBKDF2-HMAC-SHA512: key `abcdefghijklmnop`, salt 16×0x01, 100 000 rounds ⇒
`6c30ca8b15c27f6e…14ae2a4da14728e1`. The whole reader path (48-byte
preamble, AES-256-CBC, sacrificial discard) was checked against a stream
produced by `openssl enc -aes-256-cbc -nopad`.
6. **The security key is whitespace-stripped where it is typed**, not where it
is validated: `Regex.Replace(text, @"\s+", "")`
(`Form/Settings/SetupPage2a.cs:92`). `IsKeyValid` only measures length
(`Encryption.cs:235-242`), which is why the grouped display form
(`Encryption.cs:65-79`, four characters then two spaces) can be copied
between machines.
7. **`MachineName` is trimmed with `String.Trim()`** (`DATA.cs:83`), which
strips whitespace but *not* NUL. Windows pads with spaces
(`DATA.cs:88`), so this only matters for a zero-filled field; we trim NUL
as well so such a field reads as empty.
8. **The 48-byte clipboard chunk starts at offset 16**, i.e.
`PACKAGE_SIZE_EX - DATA_SIZE` (`Clipboard.cs:46, 274`), and the last chunk
is zero-filled by clearing the whole buffer first (`Clipboard.cs:281`).