Files
mac_without_borders/Sources/MWBCore/CipherStream.swift
T
lucio ee835508f4 wire-core: port DATA/PackageType, framing, magic hash and the CBC stream
Packet.swift, Framing.swift, MagicHash.swift, CipherStream.swift in
MWBCore, each constant cited to the Windows source.
2026-09-16 00:09:37 -07:00

213 lines
8.8 KiB
Swift

// 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..<count).map { _ in UInt8.random(in: UInt8.min...UInt8.max, using: &generator) }
}
/// One direction of a CBC stream: a `CCCryptor` that keeps the chaining state
/// and buffers any partial block internally, like .NET's `CryptoStream`.
///
/// `options = 0` means CBC with **no** padding. Windows configures
/// `PaddingMode.Zeros` (`Encryption.cs:96`), but zero padding only ever adds
/// bytes when a stream is closed on a partial block, and every write here is a
/// whole number of 16-byte blocks, so it never fires.
private final class CBCCryptor {
private var cryptor: CCCryptorRef?
init(encrypt: Bool, key: [UInt8], iv: [UInt8]) throws {
var ref: CCCryptorRef?
let status = key.withUnsafeBytes { keyBytes in
iv.withUnsafeBytes { ivBytes in
CCCryptorCreate(
CCOperation(encrypt ? kCCEncrypt : kCCDecrypt),
CCAlgorithm(kCCAlgorithmAES),
CCOptions(0),
keyBytes.baseAddress, keyBytes.count,
ivBytes.baseAddress,
&ref)
}
}
guard status == kCCSuccess, ref != nil else {
throw CipherError.cryptorCreationFailed(status)
}
cryptor = ref
}
deinit {
if let cryptor { CCCryptorRelease(cryptor) }
}
/// Feeds `input` through the cipher and returns whatever complete blocks
/// come out — nothing at all if `input` did not complete a block.
func update(_ input: [UInt8]) throws -> [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..<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)
}
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)
}
}