SPB Git

Repository Public

SoftwareAuthenticator.swift 8.5 KB 167 lines swift

1#if DEBUG2import CryptoKit3import Foundation45/// Minimal CBOR encoder (RFC 8949, definite lengths) — only what a WebAuthn attestation needs.6enum CBOR {7    indirect enum Value {8        case unsigned(UInt64), negative(Int64), bytes(Data), text(String), array([Value]), map([(Value, Value)])9    }10    static func encode(_ v: Value) -> Data {11        var out = Data()12        func head(_ major: UInt8, _ n: UInt64) {13            switch n {14            case 0..<24: out.append(major << 5 | UInt8(n))15            case 24..<0x100: out.append(major << 5 | 24); out.append(UInt8(n))16            case 0x100..<0x10000: out.append(major << 5 | 25); out.append(contentsOf: [UInt8(n >> 8), UInt8(n & 0xff)])17            case 0x10000..<0x1_0000_0000:18                out.append(major << 5 | 26); out.append(contentsOf: (0..<4).reversed().map { UInt8((n >> (8 * UInt64($0))) & 0xff) })19            default:20                out.append(major << 5 | 27); out.append(contentsOf: (0..<8).reversed().map { UInt8((n >> (8 * UInt64($0))) & 0xff) })21            }22        }23        func put(_ v: Value) {24            switch v {25            case .unsigned(let n): head(0, n)26            case .negative(let n): head(1, UInt64(-1 - n))27            case .bytes(let d): head(2, UInt64(d.count)); out.append(d)28            case .text(let s): let d = Data(s.utf8); head(3, UInt64(d.count)); out.append(d)29            case .array(let a): head(4, UInt64(a.count)); a.forEach(put)30            case .map(let m): head(5, UInt64(m.count)); m.forEach { put($0.0); put($0.1) }31            }32        }33        put(v)34        return out35    }36}3738/// A software WebAuthn authenticator for tests and Debug runs against a local backend (RP ID `localhost`).39///40/// It behaves like a synced platform passkey: ES256 (P-256) keys, discoverable credentials, flags UP|UV|BE|BS41/// (+AT on registration), signature counter 0, attestation format `none`. It lets the WHOLE flow run against a real42/// server without any server-side backdoor. Compiled in DEBUG builds only; private keys are test material and are43/// stored, when a `storageURL` is given, in a plain JSON file.44public final class SoftwareAuthenticator: PasskeyProvider, @unchecked Sendable {45    public struct Credential: Codable, Sendable, Equatable {46        public var id: Data47        public var privateKey: Data48        public var userHandle: Data49        public var relyingPartyID: String50        public var userName: String51    }52    public enum Behaviour: Sendable { case normal, cancel, wrongSignature }5354    private let lock = NSLock()55    private var credentials: [Credential] = []56    private var behaviourValue: Behaviour = .normal57    private var assertions = 058    private var registrations = 059    public let origin: String60    private let storageURL: URL?6162    /// - Parameters:63    ///   - origin: the origin put in `clientDataJSON` (for example `http://localhost:8760`); the server verifies it.64    ///   - storageURL: optional file keeping the credentials between launches (Debug app / UI tests).65    public init(origin: String, storageURL: URL? = nil) {66        self.origin = origin67        self.storageURL = storageURL68        if let url = storageURL, let data = try? Data(contentsOf: url),69           let list = try? JSONDecoder().decode([Credential].self, from: data) {70            credentials = list71        }72    }7374    public var behaviour: Behaviour {75        get { lock.withLock { behaviourValue } }76        set { lock.withLock { behaviourValue = newValue } }77    }78    public var storedCredentials: [Credential] { lock.withLock { credentials } }79    public var assertionCount: Int { lock.withLock { assertions } }80    public var registrationCount: Int { lock.withLock { registrations } }81    public func removeAllCredentials() { lock.withLock { credentials = [] }; persist() }8283    public func registration(_ request: PasskeyRegistrationRequest) async throws -> PasskeyRegistration {84        if behaviour == .cancel { throw PasskeyError.cancelled }85        guard request.algorithms.isEmpty || request.algorithms.contains(-7) else { throw PasskeyError.invalidOptions("ES256 not offered") }86        let existing = lock.withLock { credentials.map(\.id) }87        if request.excludedCredentialIDs.contains(where: existing.contains) {88            throw PasskeyError.failed(code: 1006, message: "A passkey of this authenticator is already registered")89        }90        let key = P256.Signing.PrivateKey()91        var id = Data(count: 20)92        id.withUnsafeMutableBytes { _ = SecRandomCopyBytes(kSecRandomDefault, 20, $0.baseAddress!) }93        let clientData = Self.clientDataJSON(type: "webauthn.create", challenge: request.challenge, origin: origin)94        let x963 = key.publicKey.x963Representation  // 0x04 || X || Y95        let cose = CBOR.encode(.map([96            (.unsigned(1), .unsigned(2)),           // kty: EC297            (.unsigned(3), .negative(-7)),          // alg: ES25698            (.negative(-1), .unsigned(1)),          // crv: P-25699            (.negative(-2), .bytes(x963.subdata(in: 1..<33))),100            (.negative(-3), .bytes(x963.subdata(in: 33..<65))),101        ]))102        var authData = Self.authenticatorDataPrefix(rpID: request.relyingPartyID, flags: 0x01 | 0x04 | 0x08 | 0x10 | 0x40)103        authData.append(Data(count: 16))                                     // AAGUID: zero (attestation none)104        authData.append(contentsOf: [UInt8(id.count >> 8), UInt8(id.count & 0xff)])105        authData.append(id)106        authData.append(cose)107        let attestation = CBOR.encode(.map([108            (.text("fmt"), .text("none")),109            (.text("attStmt"), .map([])),110            (.text("authData"), .bytes(authData)),111        ]))112        lock.withLock {113            credentials.append(Credential(id: id, privateKey: key.rawRepresentation, userHandle: request.userID,114                                          relyingPartyID: request.relyingPartyID, userName: request.userName))115            registrations += 1116        }117        persist()118        return PasskeyRegistration(credentialID: id, clientDataJSON: clientData, attestationObject: attestation,119                                   transports: ["internal"], attachment: "platform")120    }121122    public func assertion(_ request: PasskeyAssertionRequest) async throws -> PasskeyAssertion {123        let mode = behaviour124        if mode == .cancel { throw PasskeyError.cancelled }125        let candidate: Credential? = lock.withLock {126            credentials.last {127                $0.relyingPartyID == request.relyingPartyID128                    && (request.allowedCredentialIDs.isEmpty || request.allowedCredentialIDs.contains($0.id))129            }130        }131        guard let cred = candidate else { throw PasskeyError.noCredential }132        let key = try P256.Signing.PrivateKey(rawRepresentation: cred.privateKey)133        let clientData = Self.clientDataJSON(type: "webauthn.get", challenge: request.challenge, origin: origin)134        let authData = Self.authenticatorDataPrefix(rpID: request.relyingPartyID, flags: 0x01 | 0x04 | 0x08 | 0x10)135        var signed = authData136        signed.append(Data(SHA256.hash(data: clientData)))137        if mode == .wrongSignature { signed.append(0xff) }138        let signature = try key.signature(for: signed).derRepresentation139        lock.withLock { assertions += 1 }140        return PasskeyAssertion(credentialID: cred.id, clientDataJSON: clientData, authenticatorData: authData,141                                signature: signature, userHandle: cred.userHandle, attachment: "platform")142    }143144    static func clientDataJSON(type: String, challenge: Data, origin: String) -> Data {145        // Field order and formatting follow the WebAuthn serialisation algorithm (§5.8.1.1).146        let o = origin.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")147        return Data(#"{"type":"\#(type)","challenge":"\#(Base64URL.encode(challenge))","origin":"\#(o)","crossOrigin":false}"#.utf8)148    }149150    /// rpIdHash (32) || flags (1) || signCount (4, always 0 like a synced passkey).151    static func authenticatorDataPrefix(rpID: String, flags: UInt8) -> Data {152        var d = Data(SHA256.hash(data: Data(rpID.utf8)))153        d.append(flags)154        d.append(contentsOf: [0, 0, 0, 0])155        return d156    }157158    private func persist() {159        guard let url = storageURL else { return }160        let list = lock.withLock { credentials }161        guard let data = try? JSONEncoder().encode(list) else { return }162        try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)163        try? data.write(to: url, options: [.atomic])164    }165}166#endif167
Files main
Menu

Theme