diff --git a/Sources/MWBCore/CipherStream.swift b/Sources/MWBCore/CipherStream.swift new file mode 100644 index 0000000..9878f34 --- /dev/null +++ b/Sources/MWBCore/CipherStream.swift @@ -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.. [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.. 0 { // Common.cs:1543-1550 + let drop = min(sacrificialRemaining, plaintext.count) + plaintext.removeFirst(drop) + sacrificialRemaining -= drop + } + return Data(plaintext) + } +} diff --git a/Sources/MWBCore/Framing.swift b/Sources/MWBCore/Framing.swift new file mode 100644 index 0000000..924cba4 --- /dev/null +++ b/Sources/MWBCore/Framing.swift @@ -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.. 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...?/\\|[]", + ] + + /// 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.. 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"))