Cotton code
141 lines · 5.7 KB · SwiftRaw
// The WebAuthn bytes Cotton Keys' credential provider hands iOS — the second// writer of the one rule, held to the first byte for byte.//// The provider extension links no Rust core (it is CottonShareExtension's// shape: `CottonMailbox` and `CottonValues` only), so registration and// assertion are written here over CryptoKit. The rule is the core's// (`cotton_core::keys::passkey`): `PasskeyAuthenticatorTests` reads the vector// `crates/cotton-core/tests/passkey_vector.rs` writes and must make the same// COSE key, authenticatorData and attestation object from the same key.////   registration  authData = rpIdHash ‖ UP|UV|AT ‖ counter 0 ‖ AAGUID 0 ‖ len ‖ id ‖ COSE//                 object   = CBOR {"fmt": "none", "attStmt": {}, "authData": authData}//   assertion     authData = rpIdHash ‖ UP|UV ‖ counter 0//                 signature = ES256 DER over authData ‖ clientDataHash//// THE COUNTER IS ALWAYS 0, on the phone and on the Mac, as iCloud Keychain's// passkeys: several devices sign for one row and never count.//// Nothing here logs; a private key is a CryptoKit value the caller holds.import CryptoKitimport Foundation/// The provider's WebAuthn encoder.public enum PasskeyAuthenticator {    /// authenticatorData flag: the user was present.    public static let flagUP: UInt8 = 0x01    /// authenticatorData flag: the user was verified.    public static let flagUV: UInt8 = 0x04    /// authenticatorData flag: attested credential data follows.    public static let flagAT: UInt8 = 0x40    /// COSE algorithm id of ES256.    public static let es256: Int = -7    /// How many random bytes a credential id is (the core's `CREDENTIAL_ID_LEN`).    public static let credentialIdLength = 16    /// A fresh credential id: 16 random bytes.    public static func newCredentialId() -> Data {        var bytes = [UInt8](repeating: 0, count: credentialIdLength)        for index in bytes.indices { bytes[index] = UInt8.random(in: .min ... .max) }        return Data(bytes)    }    /// The COSE_Key of an ES256 public key, `{1: 2, 3: -7, -1: 1, -2: x, -3: y}`    /// in CTAP2 canonical order — the core's `cose_key`.    public static func coseKey(_ key: P256.Signing.PublicKey) -> Data {        // x963: 0x04 ‖ x (32) ‖ y (32).        let point = key.x963Representation        var out = Data([0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01])        out.append(0x21)        cborBytes(&out, point.subdata(in: 1..<33))        out.append(0x22)        cborBytes(&out, point.subdata(in: 33..<65))        return out    }    /// SHA-256 of the site id.    public static func rpIdHash(_ rpId: String) -> Data {        Data(SHA256.hash(data: Data(rpId.utf8)))    }    /// Registration's authenticatorData, the credential attested, counter 0.    public static func registrationAuthData(rpId: String, credentialId: Data, publicKey: P256.Signing.PublicKey) -> Data {        var out = head(rpId, flags: flagUP | flagUV | flagAT)        out.append(Data(repeating: 0, count: 16))  // AAGUID: none of our own        out.append(UInt8(credentialId.count >> 8))        out.append(UInt8(credentialId.count & 0xff))        out.append(credentialId)        out.append(coseKey(publicKey))        return out    }    /// The `none` attestation object over `authData`.    public static func attestationObject(authData: Data) -> Data {        var out = Data([0xa3])        cborText(&out, "fmt")        cborText(&out, "none")        cborText(&out, "attStmt")        out.append(0xa0)        cborText(&out, "authData")        cborBytes(&out, authData)        return out    }    /// Sign-in's authenticatorData: UP|UV, counter 0.    public static func assertionAuthData(rpId: String) -> Data {        head(rpId, flags: flagUP | flagUV)    }    /// The DER ES256 signature over authData ‖ clientDataHash.    public static func signature(authData: Data, clientDataHash: Data, key: P256.Signing.PrivateKey) throws -> Data {        try key.signature(for: authData + clientDataHash).derRepresentation    }    // MARK: base64url, no padding — the row's spelling    public static func base64url(_ data: Data) -> String {        data.base64EncodedString()            .replacingOccurrences(of: "+", with: "-")            .replacingOccurrences(of: "/", with: "_")            .replacingOccurrences(of: "=", with: "")    }    public static func fromBase64url(_ text: String) -> Data? {        var plain = text.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")        while plain.count % 4 != 0 { plain.append("=") }        return Data(base64Encoded: plain)    }    // MARK: the bytes    private static func head(_ rpId: String, flags: UInt8) -> Data {        var out = rpIdHash(rpId)        out.append(flags)        out.append(contentsOf: [0, 0, 0, 0])  // the counter, always 0        return out    }    private static func cborHead(_ out: inout Data, major: UInt8, length: Int) {        let major = major << 5        switch length {        case 0...23: out.append(major | UInt8(length))        case 24...0xff: out.append(contentsOf: [major | 24, UInt8(length)])        case 0x100...0xffff: out.append(contentsOf: [major | 25, UInt8(length >> 8), UInt8(length & 0xff)])        default:            out.append(major | 26)            out.append(contentsOf: [UInt8((length >> 24) & 0xff), UInt8((length >> 16) & 0xff), UInt8((length >> 8) & 0xff), UInt8(length & 0xff)])        }    }    private static func cborBytes(_ out: inout Data, _ bytes: Data) {        cborHead(&out, major: 2, length: bytes.count)        out.append(bytes)    }    private static func cborText(_ out: inout Data, _ text: String) {        let bytes = Data(text.utf8)        cborHead(&out, major: 3, length: bytes.count)        out.append(bytes)    }}