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]>
This commit is contained in:
1 parent
32a0c72944
commit
c0031c00da
4 files changed
+178
-37
No files matched your search
@@ -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..<CipherConstants.saltSize])
|
||||
let iv = Array(header[CipherConstants.saltSize...])
|
||||
return StreamMaterial(
|
||||
key: try deriveStreamKey(
|
||||
from: securityKey, salt: salt, iterations: CipherConstants.iterations),
|
||||
iv: iv, cleartextHeader: Data())
|
||||
}
|
||||
|
||||
private static func legacy(securityKey: String) throws -> 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..<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)
|
||||
}
|
||||
|
||||
if cryptor == nil { cryptor = try startStream(consuming: &input) }
|
||||
guard let cryptor else { return Data() }
|
||||
var plaintext = try cryptor.update(input)
|
||||
|
||||
@@ -209,4 +302,20 @@ public final class CipherReader {
|
||||
}
|
||||
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..<take])
|
||||
input.removeFirst(take)
|
||||
guard headerBytes.count == wanted else { return nil }
|
||||
}
|
||||
let material = try StreamMaterial.forReader(
|
||||
securityKey: securityKey, scheme: scheme, header: headerBytes)
|
||||
return try CBCCryptor(encrypt: false, key: material.key, iv: material.iv)
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,12 @@ public enum SocketStatus: Int, Sendable {
|
||||
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.
|
||||
@@ -44,6 +50,11 @@ public enum InvalidKeyReason: Sendable, Equatable {
|
||||
/// 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.
|
||||
|
||||
@@ -160,6 +160,7 @@ public struct Settings: Sendable, Equatable, Codable {
|
||||
"Name2IP": .boxed(.string("")),
|
||||
"FirstCtrlShiftS": .boxed(.bool(false)),
|
||||
"DeviceID": .boxed(.string("")),
|
||||
"MacCipherScheme": .boxed(.string(CipherScheme.legacy.rawValue)),
|
||||
]
|
||||
|
||||
// MARK: - Properties
|
||||
@@ -170,6 +171,19 @@ public struct Settings: Sendable, Equatable, Codable {
|
||||
set { setBoxed("SecurityKey", .string(newValue)) }
|
||||
}
|
||||
|
||||
/// `MacCipherScheme`: which of the two PowerToys stream layouts this Mac
|
||||
/// speaks — `"legacy"` for PowerToys ≤ 0.100 (the default, and what every
|
||||
/// stable release in the field still uses) or `"modern"` for 0.101 and
|
||||
/// later (`docs/protocol.md` §2.5).
|
||||
///
|
||||
/// This is the one property Windows does not have. It is written into the
|
||||
/// same file so a Mac needs no second settings store; a PowerToys that
|
||||
/// rewrites the file drops the key, and the default applies again.
|
||||
public var macCipherScheme: CipherScheme {
|
||||
get { CipherScheme(rawValue: string("MacCipherScheme")) ?? .legacy }
|
||||
set { setBoxed("MacCipherScheme", .string(newValue.rawValue)) }
|
||||
}
|
||||
|
||||
/// `WrapMouse` (`MatrixCircle`): the ends of the matrix join up.
|
||||
public var wrapMouse: Bool {
|
||||
get { bool("WrapMouse") }
|
||||
|
||||
@@ -37,6 +37,10 @@ public enum StatusColor {
|
||||
return NSColor(srgbRed: 1, green: 0xC0 / 255, blue: 0xCB / 255, alpha: 1)
|
||||
case .sendError: return NSColor(srgbRed: 0x80 / 255, green: 0, blue: 0, alpha: 1)
|
||||
case .connected: return NSColor(srgbRed: 0, green: 0x80 / 255, blue: 0, alpha: 1)
|
||||
// Mac-only, and painted the invalid-key brown on purpose: it is the
|
||||
// same kind of failure — nothing decrypts — with a different fix.
|
||||
case .cipherSchemeMismatch:
|
||||
return NSColor(srgbRed: 0xA5 / 255, green: 0x2A / 255, blue: 0x2A / 255, alpha: 1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,6 +60,9 @@ public enum StatusColor {
|
||||
case .timeout: return "timed out"
|
||||
case .sendError: return "send error"
|
||||
case .connected: return "connected"
|
||||
// The key is right and the Security pane's "Encryption compatibility"
|
||||
// is wrong; say which knob to turn (`docs/protocol.md` §2.5).
|
||||
case .cipherSchemeMismatch: return "wrong encryption compatibility setting"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user