Files
lucioandClaude Opus 5 c0031c00da polish P1: CipherScheme (.legacy/.modern) in the cipher stream
The legacy scheme is what every PowerToys up to v0.100.2 speaks: a fixed
PBKDF2 salt (UTF-16LE of "18446744073709551615", 40 bytes), 50 000
iterations, a fixed ASCII IV "1844674407370955" and no cleartext header —
citations to the pre-a9e1f0f20e Encryption.cs. The sacrificial block is
still the first ciphertext block under both schemes.

- CipherWriter/CipherReader take the scheme; the writer's header is 16
  bytes under .legacy and 48 under .modern, the reader consumes as many.
- MacCipherScheme setting, default legacy, Mac-only key in the same file.
- InvalidKeyReason.cipherSchemeMismatch and SocketStatus
  .cipherSchemeMismatch (raw value 100, outside the Windows range) with
  its menu text, for the diagnostic the network layer raises next.

Verified offline against Python cryptography in both directions: our
legacy writer's stream decrypts under
pbkdf2_hmac('sha512', key, '18446744073709551615'.encode('utf-16-le'),
50000, 32) + AES-CBC, and our reader recovers Python's.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-16 21:06:41 -07:00

453 lines
19 KiB
Swift

// One TCP control connection's protocol state: the handshake that decides
// whether the peer knows the security key, the trust gate that keeps everything
// else out until it does, packet reassembly, replay rejection and heartbeats.
// See docs/protocol.md §1.4, §3.2-§3.3.
//
// Ported from App/Class/SocketStuff.cs MainTCPRoutine (1261-1565) and
// TcpReceiveData (557-610), App/Core/Receiver.cs PreProcess (40-82),
// App/Core/Common.cs SendPackage/SendHeartBeat (499-513), SendAwakeBeat
// (542-559), SendByeBye (612-616) and TestSend (822-847),
// App/Form/frmScreen.cs the 100 ms timer (285-288, 555-575).
import Foundation
/// How a connection is doing, in the Windows numbering so the menu-bar colours
/// can stay the same (`SocketStatus`, `SocketStuff.cs:54-66`).
public enum SocketStatus: Int, Sendable {
/// Not in use.
case na = 0
/// Looking the peer's name up.
case resolving
/// TCP connect in progress.
case connecting
/// Connected, exchanging handshakes.
case handshaking
/// Read or write failed.
case error
/// Closed by us.
case forceClosed
/// The peer does not share our security key.
case invalidKey
/// The peer stopped answering.
case timeout
/// A write failed.
case sendError
/// Trusted and carrying traffic.
case connected
/// Mac-only, and deliberately outside the Windows range: the peer's bytes
/// frame under the *other* cipher scheme, so the security key is right and
/// the `MacCipherScheme` setting is wrong (`docs/protocol.md` §2.5). It is a
/// state of its own rather than an `.invalidKey` so the menu can say which
/// of the two settings to change.
case cipherSchemeMismatch = 100
}
/// Why a session gave up on a peer's key.
public enum InvalidKeyReason: Sendable, Equatable {
/// More than ten packets arrived before the handshake completed
/// (`SocketStuff.cs:1387-1406`).
case tooManyUntrustedPackets
/// The `HandshakeAck` nonce was not the complement we sent
/// (`SocketStuff.cs:1409-1410`).
case handshakeAckMismatch
/// The peer's first packet framed under the other `CipherScheme` and not
/// under ours: the key matches, the encryption-compatibility setting does
/// not (`docs/protocol.md` §2.5). Mac-only — Windows has one scheme per
/// build and so cannot tell these apart.
case cipherSchemeMismatch
}
/// What a session tells its owner.
public enum SessionEvent: Sendable, Equatable {
/// The connection's status changed; drive the UI from this.
case status(SocketStatus)
/// The handshake completed and the peer is trusted.
case connected(peerName: String, peerID: UInt32)
/// A trusted, non-duplicate application packet. Nothing is delivered here
/// before the handshake (CLAUDE.md invariant 2).
case packet(Packet)
/// The peer failed the key check.
case invalidKey(InvalidKeyReason)
/// The peer is us — Windows closes such a socket (`SocketStuff.cs:1430-1437`).
case selfConnection
/// Close the socket now. Always the last event of a session.
case close
}
/// Everything a session needs to know about the machine it runs on.
public struct SessionConfig: Sendable {
/// This machine's name, sent in every handshake.
public var localName: String
/// This machine's id (`MachineID` setting).
public var localID: UInt32
/// The magic number derived from the security key (`MagicHash`).
public var magic: UInt32
/// `BlockScreenSaverOnOtherMachines`, which sets the heartbeat cadence.
public var blockScreenSaver: Bool
/// The peer's name from DNS, if the caller resolved one; the `HandshakeAck`
/// name overrides it (`SocketStuff.cs:1412-1419`).
public var peerNameHint: String?
/// A session configuration.
public init(
localName: String, localID: UInt32, magic: UInt32, blockScreenSaver: Bool = true,
peerNameHint: String? = nil
) {
self.localName = localName
self.localID = localID
self.magic = magic
self.blockScreenSaver = blockScreenSaver
self.peerNameHint = peerNameHint
}
}
/// One connection's protocol logic, with no socket, timer or thread of its own.
///
/// The owner feeds it decrypted bytes, drains framed bytes to write back,
/// collects events and calls `tick` from its own timer. Not `Sendable`: one
/// connection owns one session, on one queue, alongside its `CipherWriter` and
/// `CipherReader`.
public final class Session {
/// Heartbeat every 60 s when the screen saver is being blocked
/// (`frmScreen.cs:565-570`: `count % 600` at 100 ms per tick).
public static let fastHeartbeat: TimeInterval = 60
/// Heartbeat every 300 s otherwise (`count % 3000`, `frmScreen.cs:568`).
public static let slowHeartbeat: TimeInterval = 300
/// Untrusted packets tolerated before the key is declared wrong
/// (`SocketStuff.cs:1389`).
public static let untrustedPacketLimit = 10
private let config: SessionConfig
private let sequencer: PacketSequencer
private let replay: ReplayFilter
private let isClient: Bool
private var inbox = Data()
private var outbox: [Data] = []
private var pending: [SessionEvent] = []
/// -1 once the peer is trusted, as `packageCount` is on Windows
/// (`SocketStuff.cs:1439`).
private var untrustedCount = 0
private var expectedNonce: (UInt32, UInt32, UInt32, UInt32) = (0, 0, 0, 0)
private var receiveErrors = 0
private var nextHeartbeat: TimeInterval = .greatestFiniteMagnitude
private var finished = false
/// The real-input counter as it stood when *this* session last beat —
/// `Common.lastRealInputEventCount` (`Common.cs:543`), re-recorded on the way
/// out of every beat (`:558`). It starts at zero because the Windows field
/// does, so the first beat after the process has seen any input at all is an
/// `Awake`; a spurious `Awake` only wakes a peer's screen, while a missed one
/// lets it lock under the user's hands.
private var beatInputEventCount: UInt64 = 0
/// The connection's status.
public private(set) var status: SocketStatus = .na
/// The peer's name, known once the handshake completes.
public private(set) var peerName: String?
/// The peer's machine id, taken from the `HandshakeAck`'s `Src`.
public private(set) var peerID: UInt32?
/// A session for one connection. `isClient` is whether we dialled out; it
/// changes nothing here but is what the network layer needs to decide which
/// of a pair's two connections to keep (`SocketStuff.cs:1980-2004`).
public init(
config: SessionConfig, sequencer: PacketSequencer, replay: ReplayFilter, isClient: Bool
) {
self.config = config
self.sequencer = sequencer
self.replay = replay
self.isClient = isClient
peerName = config.peerNameHint
}
/// Whether we dialled this connection out.
public var isOutbound: Bool { isClient }
// MARK: - Driving the session
/// Queues the opening handshake: ten identical `Handshake` packets, then
/// remembers the complement of their nonce as the ack we expect
/// (`SocketStuff.cs:1269-1299`).
///
/// The whole 64-byte packet starts as cryptographic randomness, so `Id`,
/// `Src` and `Des` are random too — only the type and the machine name are
/// set (`:1269-1289`).
public func start(now: TimeInterval) {
var handshake = Session.randomPacket()
try? handshake.setMachineName(config.localName)
handshake.type = .handshake
for _ in 0..<10 { sendDirect(handshake) }
let n = handshake.nonce
expectedNonce = (~n.0, ~n.1, ~n.2, ~n.3) // SocketStuff.cs:1296-1299
nextHeartbeat = now + heartbeatInterval
report(.handshaking)
}
/// Feeds decrypted socket bytes in. Handles the 32-then-32 rule itself: a
/// packet whose framing failed still occupies 64 bytes when its type byte
/// has the `Matrix` bit, which `.invalid` does (docs/protocol.md §10.1).
public func feed(_ plaintext: Data) {
inbox.append(plaintext)
while !finished {
guard inbox.count >= packageSize else { return }
let head = Framing.open(inbox.prefix(packageSize), magic: config.magic)
let size = head.type.packetSize
guard inbox.count >= size else { return }
// Re-open the whole 64 bytes for a big packet: the checksum covers
// bytes 2..31 either way, so this is what Windows does when it sets
// `package.Bytes = buf` (SocketStuff.cs:585-598).
let packet = size == packageSize ? head : Framing.open(inbox.prefix(size), magic: config.magic)
inbox.removeFirst(size)
receive(packet, bytesReceived: size)
}
}
/// A read that did not produce a whole packet, with the byte count it
/// returned.
///
/// Windows turns the read itself into a package — `PackageType.Error` for a
/// 0-byte read, `PackageType.Invalid` for a short one
/// (`SocketStuff.cs:574-578, 588-593`) — and then runs it through the *same*
/// loop body as any packet off the wire. So a malformed read spends the
/// untrusted budget exactly like a garbage packet does
/// (`:1330-1338` falls through to `:1379-1521`), and a run of short reads
/// during the handshake ends in `.invalidKey`, not `.error`. Only the 0-byte
/// kind feeds the separate six-in-a-row counter (`:1344-1364`).
public func noteReceiveError(bytesReceived: Int) {
receive(
Packet(type: bytesReceived == 0 ? .error : .invalid), bytesReceived: bytesReceived)
}
/// Reports a status the network layer knows and the session cannot see, such
/// as `.resolving` or `.sendError`.
public func report(_ new: SocketStatus) {
guard status != new else { return }
status = new
pending.append(.status(new))
}
/// Heartbeats. `inputEventCount` is the raw process-wide real-input counter,
/// which is `Event.RealInputEventCount` on Windows (`Event.cs:51-55`, bumped
/// by the hooks at `InputHook.cs:223, 345`); the owner passes the same value
/// to every session on a tick and never interprets it.
///
/// The beat is `SendAwakeBeat` (`Common.cs:545-559`): `Awake` when
/// `BlockScreenSaver` is on *and* the counter moved since this session's own
/// previous beat, `Heartbeat` otherwise, and the counter is recorded either
/// way. Keeping the comparison here rather than in the owner is what makes it
/// a since-*this*-connection's-last-beat test — sessions beat on their own
/// schedules, so a shared boundary in the owner would let a connection report
/// `Heartbeat` for input that postdates its own previous beat.
public func tick(now: TimeInterval, inputEventCount: UInt64) {
guard status == .connected, !finished, now >= nextHeartbeat else { return }
nextHeartbeat = now + heartbeatInterval
let moved = inputEventCount != beatInputEventCount
beatInputEventCount = inputEventCount // Common.cs:558
let type: PackageType = config.blockScreenSaver && moved ? .awake : .heartbeat
originate(broadcast(type))
}
/// Queues an application packet the app has **already** sequenced, for
/// delivery on this one connection.
///
/// This is the only way in for application traffic (contracts C1): the app
/// stamps one `Id` with the process-wide `PacketSequencer` and hands the
/// identical `Packet` to every target session, which is what `SkSend` does
/// with one `Id` and many sockets (`Common.cs:912-930`) and what keeps the
/// receiver's 50-entry replay ring collapsing a peer pair's two copies into
/// one (`Receiver.cs:40-82`). There is deliberately no entry point that
/// stamps an application packet per connection. `Src` is still filled in
/// here when it is `NONE`, exactly as `TcpSend` does
/// (`SocketStuff.cs:666-669`).
public func forward(_ packet: Packet) {
sendDirect(packet)
}
/// The liveness probe Windows writes before trusting a socket's "connected"
/// state (`Hi`, `TestSend`, `Common.cs:822-847`). Not sequenced, like every
/// `TcpSend`-only packet.
public func probe() {
guard let id = peerID else { return }
var p = Packet(type: .hi)
p.des = id
try? p.setMachineName(config.localName)
sendDirect(p)
}
/// Queues `ByeBye (4)` on the way out (`Common.cs:612-616`).
public func sayGoodbye() {
originate(broadcast(.byeBye))
}
/// Framed bytes to write through `CipherWriter`, in order. Drains the queue.
public func drain() -> [Data] {
defer { outbox.removeAll() }
return outbox
}
/// Everything that happened since the last call. Drains the queue.
public func events() -> [SessionEvent] {
defer { pending.removeAll() }
return pending
}
// MARK: - Receiving
/// One turn of `MainTCPRoutine`'s receive loop (`SocketStuff.cs:1326-1547`):
/// the read-error counter, then the handshake reply, then the trust gate.
/// `bytesReceived` is what the read that produced `packet` returned.
private func receive(_ packet: Packet, bytesReceived: Int) {
if packet.type == .error {
receiveErrors += 1 // SocketStuff.cs:1334
guard receiveErrors <= 5 else { // SocketStuff.cs:1344-1364
report(.error)
close()
return
}
} else {
receiveErrors = 0 // SocketStuff.cs:1366-1368
}
handle(packet, bytesReceived: bytesReceived)
}
private func handle(_ packet: Packet, bytesReceived: Int) {
// A Handshake is answered whatever the trust state, and never counts
// against the untrusted budget (SocketStuff.cs:1370-1384).
if packet.type == .handshake {
var ack = packet
ack.type = .handshakeAck
ack.src = MachineID.none // refilled with our id by sendDirect
try? ack.setMachineName(config.localName)
let n = packet.nonce
ack.nonce = (~n.0, ~n.1, ~n.2, ~n.3)
sendDirect(ack)
return
}
guard untrustedCount >= 0 else {
// Trusted. A read that returned nothing never reaches the receiver:
// the whole branch is guarded by `receivedCount > 0`
// (SocketStuff.cs:1531). Duplicate acks from the peer's ten
// handshakes are ignored rather than processed (:1540-1543).
guard bytesReceived > 0, packet.type != .handshakeAck else { return }
deliver(packet)
return
}
countUntrusted(packet)
}
/// The untrusted branch of `MainTCPRoutine` (`SocketStuff.cs:1387-1529`).
private func countUntrusted(_ packet: Packet) {
untrustedCount += 1
if untrustedCount >= Session.untrustedPacketLimit {
var reject = packet
reject.type = .invalid
for _ in 0..<10 { sendDirect(reject) } // SocketStuff.cs:1394-1397
report(.invalidKey)
pending.append(.invalidKey(.tooManyUntrustedPackets))
close()
return
}
switch packet.type {
case .handshakeAck:
acceptAck(packet)
case .mouse, .heartbeat, .heartbeatEx:
// Traffic from a peer mid-handshake is expected; give the budget
// back rather than spending it (SocketStuff.cs:1502-1515).
if untrustedCount > 5 { untrustedCount -= 1 }
default:
if untrustedCount > 5 { report(.invalidKey) } // SocketStuff.cs:1519-1521
}
}
/// The nonce check that makes a peer trusted (`SocketStuff.cs:1407-1480`).
private func acceptAck(_ packet: Packet) {
guard packet.nonce == expectedNonce else {
report(.invalidKey)
pending.append(.invalidKey(.handshakeAckMismatch))
close()
return
}
let claimed = packet.machineName ?? ""
let name = claimed.isEmpty ? (peerName ?? "") : claimed
if name.caseInsensitiveCompare(config.localName) == .orderedSame {
report(.na) // SocketStuff.cs:1433
pending.append(.selfConnection)
close()
return
}
untrustedCount = -1 // Trusted (SocketStuff.cs:1439)
peerName = name
peerID = packet.src
report(.connected)
pending.append(.connected(peerName: name, peerID: packet.src))
originate(broadcast(.heartbeat)) // SendHeartBeat(initial: true), SocketStuff.cs:1451
}
/// `Receiver.PreProcess` (`Receiver.cs:40-82`): drop what framing rejected,
/// drop the type byte Windows treats as unknown, drop replays.
private func deliver(_ packet: Packet) {
if packet.type == .invalid { return }
if packet.type.rawValue == 0 { return }
if replay.isDuplicate(packet) { return }
pending.append(.packet(packet))
}
// MARK: - Sending
/// Stamps `Id` on a packet this session **originates** and queues it.
///
/// Private on purpose (contracts C1): the only packets a connection may
/// sequence for itself are the ones that are per-connection on Windows too
/// — the handshake pair, heartbeats, `Hi` and `ByeBye`. Everything the app
/// originates is sequenced once and comes in through `forward(_:)`.
private func originate(_ packet: Packet) {
var p = packet
p.id = sequencer.next() // Common.cs:916
sendDirect(p)
}
/// Writes a packet without touching `Id`, which is what `TcpSend` does:
/// only `SkSend` sequences (`SocketStuff.cs:663-678`).
private func sendDirect(_ packet: Packet) {
guard !finished else { return }
var p = packet
if p.src == MachineID.none { p.src = config.localID } // SocketStuff.cs:666-669
outbox.append(Framing.seal(p, magic: config.magic))
}
/// A broadcast packet carrying our machine name (`SendPackage`,
/// `Common.cs:499-507`).
private func broadcast(_ type: PackageType) -> Packet {
var p = Packet(type: type)
p.des = MachineID.all
try? p.setMachineName(config.localName)
return p
}
private var heartbeatInterval: TimeInterval {
config.blockScreenSaver ? Session.fastHeartbeat : Session.slowHeartbeat
}
private func close() {
guard !finished else { return }
finished = true
pending.append(.close)
}
/// 64 cryptographically random bytes as a packet (`SocketStuff.cs:1269-1270`).
private static func randomPacket() -> Packet {
var rng = SystemRandomNumberGenerator()
let bytes = (0..<packageSizeEx).map { _ in UInt8.random(in: .min ... .max, using: &rng) }
return Packet(bytes: Data(bytes)) ?? Packet(type: .handshake)
}
}