SPB Git

Repository Public License

BridgeChannel.swift 19.9 KB 397 lines swift

1// SyncEngine — Bridge: transports, code-based pairing and the encrypted channel (docs/BRIDGE.md).2import CryptoKit3import Foundation4import Synchronization56public enum BridgeError: Error, Sendable, Equatable, CustomStringConvertible {7    case closed8    case timedOut9    case invalidCode10    /// A pairing code is good for one attempt; after any attempt, successful or not, a new code is needed.11    case codeAlreadyUsed12    case pairingFailed13    case protocolViolation(String)14    case authenticationFailed15    /// A frame arrived out of sequence: a replay, a reordering or a dropped frame.16    case sequenceViolation(expected: UInt64, received: UInt64)17    case frameTooLarge(Int)18    case incompatibleVersion(Int)19    case transport(String)2021    public var description: String {22        switch self {23        case .closed: return "The connection is closed."24        case .timedOut: return "The other device did not answer in time."25        case .invalidCode: return "A pairing code is made of digits only."26        case .codeAlreadyUsed: return "This pairing code was already used. Generate a new one."27        case .pairingFailed: return "Pairing failed: the code does not match, or the connection was tampered with. Generate a new code and try again."28        case .protocolViolation(let detail): return "The other device sent something unexpected (\(detail))."29        case .authenticationFailed: return "A message failed authentication; the connection was closed."30        case .sequenceViolation(let expected, let received): return "A message arrived out of order (expected \(expected), got \(received)); the connection was closed."31        case .frameTooLarge(let size): return "A message of \(size) bytes exceeds the limit."32        case .incompatibleVersion(let version): return "The other device speaks Bridge protocol version \(version), which this version does not support."33        case .transport(let detail): return "Connection error: \(detail)"34        }35    }36}3738/// A reliable, ordered, message-oriented link between two devices. It carries opaque frames; nothing about it39/// is trusted: confidentiality and integrity come from `BridgeSecureChannel` above it.40public protocol BridgeTransport: Sendable {41    func send(_ frame: Data) async throws42    /// The next whole frame. Throws `BridgeError.closed` when the peer closed the link.43    func receive() async throws -> Data44    func close() async45}4647/// Two connected endpoints in memory, for tests and previews.48public final class InMemoryBridgeTransport: BridgeTransport {49    /// One direction of the link: a FIFO of frames with at most a few waiting receivers.50    private actor Mailbox {51        private var frames: [Data] = []52        private var waiters: [CheckedContinuation<Data?, Never>] = []53        private var isClosed = false5455        func push(_ frame: Data) -> Bool {56            guard !isClosed else { return false }57            if waiters.isEmpty { frames.append(frame) } else { waiters.removeFirst().resume(returning: frame) }58            return true59        }6061        func pop() async -> Data? {62            if !frames.isEmpty { return frames.removeFirst() }63            if isClosed { return nil }64            return await withCheckedContinuation { waiters.append($0) }65        }6667        func close() {68            isClosed = true69            for waiter in waiters { waiter.resume(returning: nil) }70            waiters.removeAll()71        }72    }7374    private let inbox: Mailbox75    private let outbox: Mailbox7677    private init(inbox: Mailbox, outbox: Mailbox) { self.inbox = inbox; self.outbox = outbox }7879    public static func pair() -> (InMemoryBridgeTransport, InMemoryBridgeTransport) {80        let first = Mailbox(), second = Mailbox()81        return (InMemoryBridgeTransport(inbox: first, outbox: second), InMemoryBridgeTransport(inbox: second, outbox: first))82    }8384    public func send(_ frame: Data) async throws {85        guard await outbox.push(frame) else { throw BridgeError.closed }86    }8788    public func receive() async throws -> Data {89        // A cancelled receiver must not wait for ever: cancellation closes the link, like a dropped connection.90        let frame = await withTaskCancellationHandler {91            await inbox.pop()92        } onCancel: { [inbox, outbox] in93            Task { await inbox.close(); await outbox.close() }94        }95        guard let frame else { throw BridgeError.closed }96        return frame97    }9899    /// Closes both directions. Frames already delivered to the peer's queue can still be read.100    public func close() async {101        await inbox.close()102        await outbox.close()103    }104}105106/// A short numeric code shown on one device and typed on the other.107public struct BridgePairingCode: Sendable, Hashable {108    public static let defaultLength = 6109    public let digits: String110111    /// A fresh random code from the system's cryptographic generator.112    public static func generate(length: Int = defaultLength) -> BridgePairingCode {113        var generator = SystemRandomNumberGenerator()114        let count = min(max(length, 6), 12)115        return BridgePairingCode(digits: String((0..<count).map { _ in Character(String(Int.random(in: 0...9, using: &generator))) }))116    }117118    private init(digits: String) { self.digits = digits }119120    /// Parses what the user typed: spaces and dashes are ignored, anything but 6–12 digits is refused.121    public init(_ text: String) throws {122        let cleaned = text.filter { !$0.isWhitespace && $0 != "-" }123        guard (6...12).contains(cleaned.count), cleaned.allSatisfy({ $0.isASCII && $0.isNumber }) else { throw BridgeError.invalidCode }124        digits = cleaned125    }126127    /// The code in groups of three, for display.128    public var formatted: String {129        var result = ""130        for (index, character) in digits.enumerated() {131            if index > 0, index % 3 == 0 { result.append(" ") }132            result.append(character)133        }134        return result135    }136}137138/// The pairing handshake: an ephemeral X25519 key agreement in which each public key travels XOR-masked with a139/// pad derived from the pairing code (the idea of Encrypted Key Exchange), followed by key confirmation in140/// both directions.141///142/// This is **not** a standard PAKE (it is not SPAKE2, CPace or OPAQUE) and has had no cryptographic review.143/// What it is meant to give, and what it does not, is spelled out in docs/BRIDGE.md.144public enum BridgePairing {145    static let protocolVersion: UInt8 = 2146    static let label = Data("ORIX-BRIDGE-PAIR-v2".utf8)147148    enum Role: UInt8 { case initiator = 0x49, responder = 0x52 }   // "I", "R"149150    private static func random(_ count: Int) -> Data {151        var generator = SystemRandomNumberGenerator()152        return Data((0..<count).map { _ in UInt8.random(in: .min ... .max, using: &generator) })153    }154155    private static func receive(_ transport: any BridgeTransport, type: UInt8, length: Int) async throws -> Data {156        let frame = try await transport.receive()157        guard frame.count == length + 1, frame.first == type else { throw BridgeError.pairingFailed }158        return Data(frame.dropFirst())159    }160161    /// The pad that hides a public key. Only someone who knows the code can remove it; with a wrong code the162    /// result is an unrelated value, for which nobody knows a private key.163    static func mask(_ key: Data, role: Role, code: BridgePairingCode, nonces: Data) -> Data {164        let pad = HKDF<SHA256>.deriveKey(inputKeyMaterial: SymmetricKey(data: Data(code.digits.utf8)), salt: label + nonces,165                                         info: Data([role.rawValue]), outputByteCount: 32).withUnsafeBytes { Data($0) }166        var result = Data(count: 32)167        for index in 0..<32 { result[index] = key[key.startIndex + index] ^ pad[index] }168        // Bit 255 of an X25519 public key is always 0. It is left unmasked so that it stays 0 under every code:169        // otherwise half of the wrong codes could be ruled out by looking at that bit.170        result[31] = (result[31] & 0x7F) | (key[key.startIndex + 31] & 0x80)171        return result172    }173174    private struct Secrets {175        var confirmation: (initiator: Data, responder: Data)176        var initiatorToResponder: SymmetricKey177        var responderToInitiator: SymmetricKey178    }179180    private static func derive(shared: SharedSecret, code: BridgePairingCode, transcript: Data) -> Secrets {181        let hash = Data(SHA256.hash(data: label + transcript))182        func key(_ info: String) -> SymmetricKey {183            let base = shared.hkdfDerivedSymmetricKey(using: SHA256.self, salt: hash, sharedInfo: Data(info.utf8), outputByteCount: 32)184            let material = base.withUnsafeBytes { Data($0) } + Data(code.digits.utf8)185            return HKDF<SHA256>.deriveKey(inputKeyMaterial: SymmetricKey(data: material), salt: hash, info: Data(("code:" + info).utf8), outputByteCount: 32)186        }187        let confirmKey = key("confirm")188        func confirmation(_ role: Role) -> Data { Data(HMAC<SHA256>.authenticationCode(for: Data([role.rawValue]) + hash, using: confirmKey)) }189        return Secrets(confirmation: (confirmation(.initiator), confirmation(.responder)),190                       initiatorToResponder: key("i2r"), responderToInitiator: key("r2i"))191    }192193    private static func agree(_ privateKey: Curve25519.KeyAgreement.PrivateKey, with peerKey: Data) throws -> SharedSecret {194        // A value that is not a usable public key (it can only come from a wrong code or an attacker) fails here.195        guard let peer = try? Curve25519.KeyAgreement.PublicKey(rawRepresentation: peerKey),196              let shared = try? privateKey.sharedSecretFromKeyAgreement(with: peer) else { throw BridgeError.pairingFailed }197        return shared198    }199200    private static func isValid(_ confirmation: Data, _ expected: Data) -> Bool {201        guard confirmation.count == expected.count else { return false }202        var difference: UInt8 = 0203        for (x, y) in zip(confirmation, expected) { difference |= x ^ y }   // constant time204        return difference == 0205    }206207    private static func withTimeout<T: Sendable>(_ timeout: Duration, transport: any BridgeTransport,208                                                 _ body: @escaping @Sendable () async throws -> T) async throws -> T {209        let expired = Mutex(false)210        do {211            return try await withThrowingTaskGroup(of: T.self) { group in212                group.addTask { try await body() }213                group.addTask {214                    try await Task.sleep(for: timeout)215                    expired.withLock { $0 = true }216                    // Closing the transport unblocks a receive that would otherwise wait for ever.217                    await transport.close()218                    throw BridgeError.timedOut219                }220                defer { group.cancelAll() }221                guard let result = try await group.next() else { throw BridgeError.timedOut }222                return result223            }224        } catch {225            await transport.close()226            if expired.withLock({ $0 }) { throw BridgeError.timedOut }227            // During the handshake a link closed by the other side means it rejected us.228            if let bridge = error as? BridgeError, bridge != .closed { throw bridge }229            throw BridgeError.pairingFailed230        }231    }232233    /// Run on the device where the user **typed** the code. Returns an encrypted channel, or throws234    /// `pairingFailed` (and closes the transport) if the other side does not know the same code.235    public static func initiate(code: BridgePairingCode, over transport: any BridgeTransport, timeout: Duration = .seconds(60)) async throws -> BridgeSecureChannel {236        try await withTimeout(timeout, transport: transport) {237            let privateKey = Curve25519.KeyAgreement.PrivateKey()238            let publicKey = privateKey.publicKey.rawRepresentation239            let nonce = random(16)240            let masked = mask(publicKey, role: .initiator, code: code, nonces: nonce)241            try await transport.send(Data([0x01, protocolVersion]) + nonce + masked)242            let answer = try await receive(transport, type: 0x02, length: 1 + 16 + 32 + 32)243            guard answer.first == protocolVersion else { throw BridgeError.incompatibleVersion(Int(answer.first ?? 0)) }244            let peerNonce = Data(answer.dropFirst().prefix(16)), peerMasked = Data(answer.dropFirst(17).prefix(32)), peerConfirmation = Data(answer.suffix(32))245            let peerKey = mask(peerMasked, role: .responder, code: code, nonces: nonce + peerNonce)246            let shared = try agree(privateKey, with: peerKey)247            let secrets = derive(shared: shared, code: code, transcript: nonce + peerNonce + masked + peerMasked + publicKey + peerKey)248            guard isValid(peerConfirmation, secrets.confirmation.responder) else { throw BridgeError.pairingFailed }249            try await transport.send(Data([0x03]) + secrets.confirmation.initiator)250            return BridgeSecureChannel(transport: transport, sendKey: secrets.initiatorToResponder, receiveKey: secrets.responderToInitiator,251                                       sendDirection: Role.initiator.rawValue, receiveDirection: Role.responder.rawValue)252        }253    }254255    fileprivate static func respond(code: BridgePairingCode, over transport: any BridgeTransport, timeout: Duration) async throws -> BridgeSecureChannel {256        try await withTimeout(timeout, transport: transport) {257            let hello = try await receive(transport, type: 0x01, length: 1 + 16 + 32)258            guard hello.first == protocolVersion else { throw BridgeError.incompatibleVersion(Int(hello.first ?? 0)) }259            let peerNonce = Data(hello.dropFirst().prefix(16)), peerMasked = Data(hello.suffix(32))260            let privateKey = Curve25519.KeyAgreement.PrivateKey()261            let publicKey = privateKey.publicKey.rawRepresentation262            let nonce = random(16)263            let masked = mask(publicKey, role: .responder, code: code, nonces: peerNonce + nonce)264            let peerKey = mask(peerMasked, role: .initiator, code: code, nonces: peerNonce)265            let shared = try agree(privateKey, with: peerKey)266            let secrets = derive(shared: shared, code: code, transcript: peerNonce + nonce + peerMasked + masked + peerKey + publicKey)267            try await transport.send(Data([0x02, protocolVersion]) + nonce + masked + secrets.confirmation.responder)268            let peerConfirmation = try await receive(transport, type: 0x03, length: 32)269            guard isValid(peerConfirmation, secrets.confirmation.initiator) else { throw BridgeError.pairingFailed }270            return BridgeSecureChannel(transport: transport, sendKey: secrets.responderToInitiator, receiveKey: secrets.initiatorToResponder,271                                       sendDirection: Role.responder.rawValue, receiveDirection: Role.initiator.rawValue)272        }273    }274}275276/// The offer made by the device that **shows** the code. It accepts exactly one pairing attempt: whatever its277/// outcome, the code is spent and a second `accept` throws `codeAlreadyUsed`. This single-attempt rule is what278/// limits an attacker to one guess per code.279public actor BridgePairingOffer {280    public nonisolated let code: BridgePairingCode281    private var isSpent = false282283    public init(code: BridgePairingCode = .generate()) { self.code = code }284285    public var hasBeenUsed: Bool { isSpent }286287    public func accept(over transport: any BridgeTransport, timeout: Duration = .seconds(60)) async throws -> BridgeSecureChannel {288        guard !isSpent else {289            await transport.close()290            throw BridgeError.codeAlreadyUsed291        }292        isSpent = true293        return try await BridgePairing.respond(code: code, over: transport, timeout: timeout)294    }295}296297/// An authenticated, encrypted, ordered message channel over a transport.298///299/// Each direction has its own ChaCha20-Poly1305 key and a 64-bit sequence number that is both the nonce and300/// part of the authenticated data. The receiver accepts only the next expected number, so a replayed, dropped,301/// duplicated or reordered frame is rejected; so is any modified frame. After any rejection the channel is302/// closed: there is no way to resynchronise.303public actor BridgeSecureChannel {304    public static let maximumMessageBytes = 16 * 1024 * 1024305    static let context = Data("ORIX-BRIDGE-v1".utf8)306307    private let transport: any BridgeTransport308    private let sendKey: SymmetricKey309    private let receiveKey: SymmetricKey310    private let sendDirection: UInt8311    private let receiveDirection: UInt8312    private var sendSequence: UInt64 = 0313    private var receiveSequence: UInt64 = 0314    private var isClosed = false315    private var sendTail: Task<Void, any Error>?316317    init(transport: any BridgeTransport, sendKey: SymmetricKey, receiveKey: SymmetricKey, sendDirection: UInt8, receiveDirection: UInt8) {318        self.transport = transport; self.sendKey = sendKey; self.receiveKey = receiveKey319        self.sendDirection = sendDirection; self.receiveDirection = receiveDirection320    }321322    private static func sequenceBytes(_ sequence: UInt64) -> Data { withUnsafeBytes(of: sequence.bigEndian) { Data($0) } }323324    private static func nonce(_ sequence: UInt64) throws -> ChaChaPoly.Nonce {325        try ChaChaPoly.Nonce(data: Data(count: 4) + sequenceBytes(sequence))326    }327328    private func seal(_ message: Data) throws -> Data {329        guard !isClosed else { throw BridgeError.closed }330        guard message.count <= Self.maximumMessageBytes else { throw BridgeError.frameTooLarge(message.count) }331        guard sendSequence < UInt64.max - 1 else { throw BridgeError.closed }332        let sequence = sendSequence333        sendSequence += 1334        let header = Self.sequenceBytes(sequence)335        let box = try ChaChaPoly.seal(message, using: sendKey, nonce: try Self.nonce(sequence),336                                      authenticating: Self.context + Data([sendDirection]) + header)337        return header + box.ciphertext + box.tag338    }339340    /// Sends one message. Calls made concurrently are sent in the order they were made.341    public func send(_ message: Data) async throws {342        // Sealing assigns the sequence number; the write must hit the transport in that same order, so each343        // send waits for the previous one.344        let previous = sendTail345        let task = Task { [transport] in346            _ = try? await previous?.value347            let frame = try self.seal(message)348            try await transport.send(frame)349        }350        sendTail = task351        do {352            try await task.value353        } catch {354            await shutDown()355            throw error356        }357    }358359    /// The next message, verified. Any failure closes the channel.360    public func receive() async throws -> Data {361        guard !isClosed else { throw BridgeError.closed }362        let frame: Data363        do { frame = try await transport.receive() } catch {364            await shutDown()365            throw error366        }367        do {368            guard frame.count >= 8 + 16, frame.count <= Self.maximumMessageBytes + 24 else { throw BridgeError.protocolViolation("frame size") }369            let header = Data(frame.prefix(8))370            let sequence = header.reduce(UInt64(0)) { ($0 << 8) | UInt64($1) }371            guard sequence == receiveSequence else { throw BridgeError.sequenceViolation(expected: receiveSequence, received: sequence) }372            let body = frame.dropFirst(8)373            guard let box = try? ChaChaPoly.SealedBox(nonce: try Self.nonce(sequence), ciphertext: body.dropLast(16), tag: body.suffix(16)),374                  let message = try? ChaChaPoly.open(box, using: receiveKey, authenticating: Self.context + Data([receiveDirection]) + header) else {375                throw BridgeError.authenticationFailed376            }377            receiveSequence += 1378            return message379        } catch {380            await shutDown()381            throw error382        }383    }384385    private func shutDown() async {386        guard !isClosed else { return }387        isClosed = true388        await transport.close()389    }390391    public func close() async {392        // Let queued sends reach the transport before closing it.393        _ = try? await sendTail?.value394        await shutDown()395    }396}397
Files main
Menu

Theme