// 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.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. 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) } /// 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 { /// 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`). 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 } /// 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], iterations: UInt32) 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), iterations, out.baseAddress, out.count) } } } guard status == kCCSuccess else { throw CipherError.keyDerivationFailed } 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 /// 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.. [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: 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`. `.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. 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 = material.cleartextHeader + 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, 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`. 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 /// 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 { cryptor = try startStream(consuming: &input) } 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) } /// Takes the peer's cleartext header off the front of `input` and builds /// the cipher from it. Returns `nil` while the header is still incomplete, /// which under `.legacy` — where there is no header — never happens. private func startStream(consuming input: inout [UInt8]) throws -> CBCCryptor? { let wanted = scheme.cleartextHeaderSize if wanted > 0 { let take = min(wanted - headerBytes.count, input.count) headerBytes.append(contentsOf: input[0..