PasskeyRegistration.kt

12.5 KB · raw

1package com.peachpasswords.passkeys23import com.peachpasswords.vault.PasskeyData4import com.peachpasswords.vault.VaultEntry5import java.security.KeyPairGenerator6import java.security.SecureRandom7import java.security.interfaces.ECPrivateKey8import java.security.interfaces.ECPublicKey9import java.security.spec.ECGenParameterSpec10import java.util.Base6411import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters12import kotlinx.serialization.json.Json13import kotlinx.serialization.json.JsonObject14import kotlinx.serialization.json.JsonPrimitive15import kotlinx.serialization.json.buildJsonArray16import kotlinx.serialization.json.buildJsonObject17import kotlinx.serialization.json.contentOrNull18import kotlinx.serialization.json.intOrNull19import kotlinx.serialization.json.jsonArray20import kotlinx.serialization.json.jsonObject21import kotlinx.serialization.json.jsonPrimitive22import kotlinx.serialization.json.put2324data class PasskeyRegistrationResult(25    val entryDraft: VaultEntry,26    val responseJson: String,27)2829object PasskeyRegistration {30    private val json = Json { ignoreUnknownKeys = true }31    private val random = SecureRandom()32    private val urlEncoder = Base64.getUrlEncoder().withoutPadding()3334    fun build(35        requestJson: String,36        origin: String?,37        now: Long = System.currentTimeMillis(),38        // Set to true only when a biometric / device-credential prompt has39        // actually succeeded for this registration. Defaults to false so40        // callers that bypass the prompt still produce a valid flag byte41        // (UV=0) rather than the old hard-coded UV=1 claim.42        userVerified: Boolean = false,43    ): PasskeyRegistrationResult? {44        val request = runCatching { json.parseToJsonElement(requestJson).jsonObject }.getOrNull() ?: return null45        // F2 fail-closed: clientDataJSON carries ONLY the framework-verified46        // caller origin — never a synthesized https://<rpId>. F1: web origins47        // must sit inside the rpId's registrable domain; native-app origins48        // (android:apk-key-hash:*) bind the credential to the calling app.49        val callerOrigin = origin?.takeIf { it.isNotBlank() } ?: return null50        val rp = request["rp"]?.jsonObject ?: return null51        val user = request["user"]?.jsonObject ?: return null52        val rpId = rp["id"]?.jsonPrimitive?.contentOrNull ?: return null53        if (PasskeyCallerOrigin.isWebOrigin(callerOrigin) &&54            !PasskeyCallerOrigin.rpIdMatchesOrigin(rpId, callerOrigin)55        ) {56            return null57        }58        val rpName = rp["name"]?.jsonPrimitive?.contentOrNull ?: rpId59        val userHandle = user["id"]?.jsonPrimitive?.contentOrNull ?: return null60        val userName = user["name"]?.jsonPrimitive?.contentOrNull ?: return null61        val userDisplayName = user["displayName"]?.jsonPrimitive?.contentOrNull ?: userName62        val challenge = request["challenge"]?.jsonPrimitive?.contentOrNull ?: return null63        val algorithm = pickAlgorithm(request["pubKeyCredParams"]) ?: return null6465        val keyMaterial = generateKeyMaterial(algorithm)66        val credentialId = ByteArray(32).also(random::nextBytes)67        val publicKeyCose = keyMaterial.publicKeyCose68        // Peach's vault always permits the credential's private key to leave the69        // device via PeachScript export or paired-device sync, so every freshly70        // registered passkey is by definition backup-eligible. backupState stays71        // false: at the moment of registration the credential has not yet been72        // mirrored anywhere — that fact is written here so the BE/BS bits in the73        // authenticator data never disagree with the persisted record.74        val backupEligible = true75        val backupState = false76        val authData = buildAttestationAuthData(rpId, credentialId, publicKeyCose, registrationFlags(userVerified))77        val attestationObject = Cbor.map(78            "fmt" to Cbor.text("none"),79            "attStmt" to Cbor.map(),80            "authData" to Cbor.bytes(authData),81        )82        val clientDataJson = clientDataJson("webauthn.create", challenge, callerOrigin)83        val passkey = PasskeyData(84            credentialId = b64(credentialId),85            publicKeyCose = b64(publicKeyCose),86            privateKeyJwk = keyMaterial.privateKeyJwk,87            rpId = rpId,88            rpName = rpName,89            userHandle = userHandle,90            userName = userName,91            userDisplayName = userDisplayName,92            algorithm = algorithm,93            signCount = 0,94            aaguid = b64(ByteArray(16)),95            backupEligible = backupEligible,96            backupState = backupState,97            transports = listOf("internal"),98            createdAt = now,99            callerOrigin = callerOrigin,100        )101        val entry = VaultEntry(102            id = "",103            type = "login",104            title = rpName,105            username = userName,106            url = "https://$rpId",107            passkey = passkey,108            createdAt = 0,109            modifiedAt = 0,110        )111        val responseJson = json.encodeToString(112            JsonObject.serializer(),113            buildJsonObject {114                put("id", passkey.credentialId)115                put("rawId", passkey.credentialId)116                put("type", "public-key")117                put("response", buildJsonObject {118                    put("clientDataJSON", b64(clientDataJson))119                    put("authenticatorData", b64(authData))120                    put("attestationObject", b64(attestationObject))121                    put("transports", buildJsonArray { add(JsonPrimitive("internal")) })122                    put("publicKey", b64(keyMaterial.publicKeySpki))123                    put("publicKeyAlgorithm", algorithm)124                })125                put("authenticatorAttachment", "platform")126                put("clientExtensionResults", buildJsonObject {})127            },128        )129        return PasskeyRegistrationResult(entryDraft = entry, responseJson = responseJson)130    }131132    private data class KeyMaterial(133        val publicKeyCose: ByteArray,134        val publicKeySpki: ByteArray,135        val privateKeyJwk: String,136    )137138    private fun pickAlgorithm(value: kotlinx.serialization.json.JsonElement?): Int? {139        val params = runCatching { value?.jsonArray }.getOrNull() ?: return -7140        val offered = params.mapNotNull { item ->141            runCatching { item.jsonObject["alg"]?.jsonPrimitive?.intOrNull }.getOrNull()142        }.toSet()143        return when {144            -8 in offered -> -8145            -7 in offered -> -7146            else -> null147        }148    }149150    private fun generateKeyMaterial(algorithm: Int): KeyMaterial =151        if (algorithm == -8) generateEd25519KeyMaterial() else generateEs256KeyMaterial()152153    private fun generateEs256KeyMaterial(): KeyMaterial {154        val keyPair = KeyPairGenerator.getInstance("EC").apply {155            initialize(ECGenParameterSpec("secp256r1"))156        }.generateKeyPair()157        val privateKey = keyPair.private as ECPrivateKey158        val publicKey = keyPair.public as ECPublicKey159        val publicKeyCose = Cbor.map(160            1 to Cbor.uint(2),161            3 to Cbor.nint(-7),162            -1 to Cbor.uint(1),163            -2 to Cbor.bytes(publicKey.w.affineX.toFixed32()),164            -3 to Cbor.bytes(publicKey.w.affineY.toFixed32()),165        )166        return KeyMaterial(167            publicKeyCose = publicKeyCose,168            publicKeySpki = publicKey.encoded,169            privateKeyJwk = privateEs256Jwk(privateKey, publicKey),170        )171    }172173    private fun generateEd25519KeyMaterial(): KeyMaterial {174        val privateKey = Ed25519PrivateKeyParameters(random)175        val publicKey = privateKey.generatePublicKey().encoded176        val seed = privateKey.encoded177        val publicKeyCose = Cbor.map(178            1 to Cbor.uint(1),179            3 to Cbor.nint(-8),180            -1 to Cbor.uint(6),181            -2 to Cbor.bytes(publicKey),182        )183        val privateKeyJwk = json.encodeToString(184            JsonObject.serializer(),185            buildJsonObject {186                put("kty", "OKP")187                put("crv", "Ed25519")188                put("d", b64(seed))189                put("x", b64(publicKey))190            },191        )192        return KeyMaterial(193            publicKeyCose = publicKeyCose,194            publicKeySpki = ed25519Spki(publicKey),195            privateKeyJwk = privateKeyJwk,196        )197    }198199    private fun buildAttestationAuthData(rpId: String, credentialId: ByteArray, publicKeyCose: ByteArray, flags: Int): ByteArray {200        val base = ByteArray(37)201        java.security.MessageDigest.getInstance("SHA-256").digest(rpId.toByteArray(Charsets.UTF_8)).copyInto(base, 0)202        // UP=1 (implicit in the credential pick); BE set because Peach vaults203        // are exportable/syncable by construction; AT set because attested204        // credential data is always included at registration; UV reflects an205        // actual user-verification ceremony performed by the caller — never206        // assume it. H-07 fix: the flag byte used to hard-code UV=1 without207        // running any ceremony, which is precisely the misleading-claim bug.208        base[32] = flags.toByte()209        val length = byteArrayOf(((credentialId.size ushr 8) and 0xff).toByte(), (credentialId.size and 0xff).toByte())210        return base + ByteArray(16) + length + credentialId + publicKeyCose211    }212213    private const val FLAG_UP: Int = 0x01214    private const val FLAG_UV: Int = 0x04215    private const val FLAG_BE: Int = 0x08216    private const val FLAG_AT: Int = 0x40217218    // AT (0x40) is always included for registration because the response219    // carries attested credential data; BE (0x08) is set because Peach220    // vaults are exportable/syncable by construction; UP (0x01) is implicit221    // in the user picking a credential. UV (0x04) is set only when the222    // caller actually performed user verification.223    private fun registrationFlags(userVerified: Boolean): Int =224        FLAG_UP or FLAG_BE or FLAG_AT or (if (userVerified) FLAG_UV else 0)225226    private fun clientDataJson(type: String, challenge: String, origin: String): ByteArray =227        json.encodeToString(228            JsonObject.serializer(),229            buildJsonObject {230                put("type", type)231                put("challenge", challenge)232                put("origin", origin)233                put("crossOrigin", JsonPrimitive(false))234            },235        ).toByteArray(Charsets.UTF_8)236237    private fun privateEs256Jwk(privateKey: ECPrivateKey, publicKey: ECPublicKey): String =238        json.encodeToString(239            JsonObject.serializer(),240            buildJsonObject {241                put("kty", "EC")242                put("crv", "P-256")243                put("d", b64(privateKey.s.toFixed32()))244                put("x", b64(publicKey.w.affineX.toFixed32()))245                put("y", b64(publicKey.w.affineY.toFixed32()))246            },247        )248249    private fun b64(data: ByteArray): String = urlEncoder.encodeToString(data)250251    private fun ed25519Spki(publicKey: ByteArray): ByteArray =252        byteArrayOf(253            0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,254        ) + publicKey255}256257private object Cbor {258    fun uint(value: Int) = integer(value)259    fun nint(value: Int) = integer(value)260    fun bytes(value: ByteArray) = major(2, value.size) + value261    fun text(value: String): ByteArray {262        val bytes = value.toByteArray(Charsets.UTF_8)263        return major(3, bytes.size) + bytes264    }265    fun map(vararg entries: Pair<Any, ByteArray>): ByteArray {266        val body = entries.flatMap { (key, value) ->267            val encodedKey = when (key) {268                is Int -> integer(key)269                is String -> text(key)270                else -> error("unsupported cbor key")271            }272            listOf(encodedKey, value)273        }.fold(ByteArray(0)) { acc, bytes -> acc + bytes }274        return major(5, entries.size) + body275    }276    private fun integer(value: Int): ByteArray =277        if (value >= 0) major(0, value) else major(1, -1 - value)278    private fun major(type: Int, value: Int): ByteArray = when {279        value < 24 -> byteArrayOf(((type shl 5) or value).toByte())280        value < 0x100 -> byteArrayOf(((type shl 5) or 24).toByte(), value.toByte())281        value < 0x10000 -> byteArrayOf(((type shl 5) or 25).toByte(), (value ushr 8).toByte(), value.toByte())282        else -> error("cbor length too large")283    }284}285286private fun java.math.BigInteger.toFixed32(): ByteArray {287    val raw = toByteArray()288    val unsigned = if (raw.size > 1 && raw[0] == 0.toByte()) raw.copyOfRange(1, raw.size) else raw289    return ByteArray(32).also { unsigned.copyInto(it, 32 - unsigned.size) }290}