diff --git a/Sources/MWBCore/CipherStream.swift b/Sources/MWBCore/CipherStream.swift index 9878f34..c5bf9e3 100644 --- a/Sources/MWBCore/CipherStream.swift +++ b/Sources/MWBCore/CipherStream.swift @@ -1,10 +1,16 @@ // 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. +// through, and the PBKDF2 derivation behind it. See docs/protocol.md §2.2-§2.5. // // Ported from App/Core/Encryption.cs (92-171) and // App/Core/Common.cs SendOrReceiveARandomDataBlockPerInitialIV (1528-1558), // wired at App/Class/SocketStuff.cs:102-123. // +// Two schemes live here, because two vintages of PowerToys are in the field: +// the legacy fixed salt/IV of every release up to v0.100.2, and the +// per-connection cleartext header that PR #48742 (`a9e1f0f20e`, 2026-06-22) +// introduced for v0.101. Citations to the legacy constants are to the +// pre-change file, `git show a9e1f0f20e^:.../App/Core/Encryption.cs`. +// // This is the only file in the project that touches CommonCrypto (CLAUDE.md, // Swift standards): CryptoKit has no CBC mode. @@ -22,6 +28,33 @@ public enum CipherError: Error, Sendable, Hashable { case cryptorUpdateFailed(Int32) } +/// Which of the two PowerToys stream layouts a connection speaks +/// (`docs/protocol.md` §2.3, §2.5). +/// +/// There is no negotiation: both vintages of Windows write their preamble +/// first and never adapt, so the user picks the one their PCs run. +public enum CipherScheme: String, Sendable, Hashable, CaseIterable, Codable { + /// PowerToys v0.100.2 and earlier: fixed salt and IV, no cleartext header. + case legacy + /// PowerToys v0.101 and later: a per-connection random salt and IV sent in + /// the clear ahead of the ciphertext. + case modern + + /// The other scheme, which is what the mismatch diagnostic replays the + /// peer's first bytes under (`docs/protocol.md` §2.5). + public var other: CipherScheme { self == .legacy ? .modern : .legacy } + + /// Cleartext bytes the writer puts on the wire before any ciphertext: the + /// 16-byte salt and 16-byte IV under `.modern`, nothing under `.legacy`. + var cleartextHeaderSize: Int { + self == .modern ? CipherConstants.saltSize + CipherConstants.blockSize : 0 + } + + /// Bytes a reader must consume before the stream is packet-aligned: the + /// cleartext header plus the encrypted sacrificial block. + public var preambleSize: Int { cleartextHeaderSize + CipherConstants.blockSize } +} + /// Constants shared by both directions, all dictated by the Windows side. enum CipherConstants { /// AES block size in bytes (`SymAlBlockSize`, `Encryption.cs:32`). @@ -34,10 +67,29 @@ enum CipherConstants { static let derivedKeyLength = 32 } +/// The fixed material every PowerToys up to v0.100.2 keys its streams with. +/// Citations are to the pre-`a9e1f0f20e` `Encryption.cs`. +enum LegacyCipherConstants { + /// `InitialIV = ulong.MaxValue.ToString()` (`Encryption.cs:41`). + static let initialIV = "18446744073709551615" + /// `Common.GetBytesU(InitialIV)` (`Encryption.cs:126`): UTF-16LE, so 40 + /// bytes for these 20 digits (`Common.cs:407-410`). + static let salt: [UInt8] = initialIV.utf16.flatMap { + [UInt8(truncatingIfNeeded: $0), UInt8(truncatingIfNeeded: $0 >> 8)] + } + /// 50 000 PBKDF2 iterations, not 100 000 (`Encryption.cs:127`). + static let iterations: UInt32 = 50_000 + /// `GenLegalIV` (`Encryption.cs:140-154`): the ASCII of `InitialIV` cut to + /// the 16-byte block size — `"1844674407370955"`. + static let iv: [UInt8] = Array(initialIV.utf8.prefix(CipherConstants.blockSize)) +} + /// `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] { +func deriveStreamKey(from securityKey: String, salt: [UInt8], iterations: UInt32) throws + -> [UInt8] +{ let password = Array(securityKey.utf8) var derived = [UInt8](repeating: 0, count: CipherConstants.derivedKeyLength) @@ -50,7 +102,7 @@ func deriveStreamKey(from securityKey: String, salt: [UInt8]) throws -> [UInt8] passwordBytes.count, saltBytes.baseAddress, saltBytes.count, CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA512), - CipherConstants.iterations, + iterations, out.baseAddress, out.count) } } @@ -59,6 +111,55 @@ func deriveStreamKey(from securityKey: String, salt: [UInt8]) throws -> [UInt8] return derived } +/// The key and IV one direction of a stream runs on, plus the cleartext header +/// that goes on the wire ahead of it. +struct StreamMaterial { + let key: [UInt8] + let iv: [UInt8] + /// Empty under `.legacy`; the salt and IV under `.modern`. + let cleartextHeader: Data + + /// Fresh material for a writer: fixed under `.legacy`, freshly random under + /// `.modern` (`Encryption.cs:124-129`). + static func forWriter(securityKey: String, scheme: CipherScheme) throws -> StreamMaterial { + switch scheme { + case .legacy: + return try legacy(securityKey: securityKey) + case .modern: + let salt = randomBytes(CipherConstants.saltSize) + let iv = randomBytes(CipherConstants.blockSize) + return StreamMaterial( + key: try deriveStreamKey( + from: securityKey, salt: salt, iterations: CipherConstants.iterations), + iv: iv, cleartextHeader: Data(salt) + Data(iv)) + } + } + + /// Material for a reader, from the peer's cleartext header — which is + /// `scheme.cleartextHeaderSize` bytes long, and so empty under `.legacy`. + static func forReader(securityKey: String, scheme: CipherScheme, header: [UInt8]) throws + -> StreamMaterial + { + guard scheme == .modern, header.count == scheme.cleartextHeaderSize else { + return try legacy(securityKey: securityKey) + } + let salt = Array(header[0.. StreamMaterial { + StreamMaterial( + key: try deriveStreamKey( + from: securityKey, salt: LegacyCipherConstants.salt, + iterations: LegacyCipherConstants.iterations), + iv: LegacyCipherConstants.iv, cleartextHeader: Data()) + } +} + /// `count` cryptographically random bytes. /// /// `SystemRandomNumberGenerator` is documented as cryptographically secure on @@ -133,24 +234,26 @@ private final class CBCCryptor { 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. + /// Everything that must reach the peer before the first packet: under + /// `.modern` the 16-byte salt and 16-byte IV in the clear + /// (`Encryption.cs:124-129`), and under either scheme the encrypted 16-byte + /// sacrificial block (`Common.cs:1528-1541`, written through the cipher + /// stream at `SocketStuff.cs:105`). So it is 48 bytes under `.modern` and + /// 16 under `.legacy`. 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) + /// Starts a stream under `securityKey`. `.legacy` uses the fixed salt and + /// IV of PowerToys ≤ 0.100; `.modern` a fresh random pair per connection. + public init(securityKey: String, scheme: CipherScheme = .legacy) throws { + let material = try StreamMaterial.forWriter(securityKey: securityKey, scheme: scheme) + cryptor = try CBCCryptor(encrypt: true, key: material.key, iv: material.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. + // first real packet is never the block the IV directly protects. Under + // `.legacy` that block is the only thing standing between a fixed IV + // and the first packet, which is why it exists at all. let sacrificial = try cryptor.update(randomBytes(CipherConstants.blockSize)) - header = Data(salt) + Data(iv) + Data(sacrificial) + header = material.cleartextHeader + Data(sacrificial) } /// Encrypts `plaintext` and returns the ciphertext to write to the socket. @@ -161,20 +264,23 @@ public final class CipherWriter { /// 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`. +/// Consumes the peer's cleartext salt+IV header, when the scheme has one, 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 let scheme: CipherScheme 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) { + /// Prepares to read a stream encrypted under `securityKey`. Under `.modern` + /// nothing is derived until the peer's salt arrives; under `.legacy` the + /// material is fixed and derived on the first byte. + public init(securityKey: String, scheme: CipherScheme = .legacy) { self.securityKey = securityKey + self.scheme = scheme } /// Feeds raw bytes from the socket and returns the packet bytes they @@ -185,20 +291,7 @@ public final class CipherReader { /// 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.. CBCCryptor? { + let wanted = scheme.cleartextHeaderSize + if wanted > 0 { + let take = min(wanted - headerBytes.count, input.count) + headerBytes.append(contentsOf: input[0..