DeviceManifestSupport.kt

14.9 KB · raw

1package com.peachpasswords.sync23import kotlinx.serialization.builtins.serializer4import kotlinx.serialization.json.Json5import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters67/** 0x05 adds signed per-issuer revocation records to the vouch graph. */8const val DEVICE_MANIFEST_VERSION = 0x059const val MAX_VOUCH_DEPTH = 310private const val DEVICE_MANIFEST_FRESHNESS_MS = 5 * 60_000L11/**12 * Upper bounds on what verifyDeviceManifest will accept. A pathological peer13 * could otherwise craft a manifest that consumes unbounded memory or skips14 * sanity checks (e.g. `issuedAt = Long.MIN_VALUE` bypasses `abs(...) > window`15 * because `abs(Long.MIN_VALUE)` is still negative). These caps match the16 * realistic limits of the pairing protocol: a handful of paired devices, a17 * bounded revocation list, and string fields long enough for any honest use.18 */19private const val MAX_MANIFEST_DEVICES = 25620private const val MAX_MANIFEST_REVOCATIONS = 50021private const val MAX_MANIFEST_STRING = 25622/**23 * Display/storage bound for device names, matching the browser's24 * MAX_DEVICE_NAME_CHARS (shared/sync-limits.ts) and both platforms' local25 * setDeviceName bound. Inbound seams cap rather than reject so old peers26 * with long-but-honest names keep syncing; a device name was never a27 * 256-char string.28 */29internal const val MAX_DEVICE_NAME_CHARS = 643031/** Truncate a peer- or user-supplied device name to the shared bound. */32internal fun capDeviceName(name: String): String =33    if (name.length > MAX_DEVICE_NAME_CHARS) name.take(MAX_DEVICE_NAME_CHARS) else name34internal const val NO_KEY_SENTINEL = "0000000000000000000000000000000000000000000000000000000000000000"3536/**37 * Fully staged membership change. Implementations must linearize the whole38 * batch; callers hold the vault session epoch fence while invoking it, so a39 * lock/re-unlock cannot observe or leave behind a half-applied manifest.40 */41data class DeviceManifestRegistryBatch(42    val incomingRevocations: List<DeviceRevocation>,43    val removals: Set<String>,44    val upserts: List<PairedDevice>,45)4647interface PairedDeviceRegistry {48    fun getAll(): List<PairedDevice>49    fun get(id: String): PairedDevice?50    fun getByPubkey(pubkeyHex: String): PairedDevice? =51        getAll().firstOrNull {52            it.longTermPublicKeyHex?.let { key -> CryptoCompare.hex(key, pubkeyHex) } == true53        }54    fun upsert(device: PairedDevice)55    fun remove(deviceId: String) {}56    fun listRevocations(): List<DeviceRevocation> = emptyList()5758    /**59     * Immutable issuer signing-key history. Implementations must append only;60     * the default keeps lightweight test registries source-compatible.61     */62    fun issuerSigningKeys(issuerDeviceId: String): Set<String> = emptySet()63    fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean = true6465    /** Commit a complete staged manifest as one logical registry mutation. */66    fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean6768    /** Returns the ids that were not already revoked. */69    fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> = emptyList()7071    /**72     * True when either the id or the long-term key is under a terminal73     * revocation. `deviceId` is a self-asserted string in a manifest, so74     * keying terminality on it alone is bypassed by re-vouching a revoked75     * device's key under a fresh id. The key is what a revoked device still76     * holds, so it is what terminality has to follow. `0`×64 is the "no key was77     * ever stored" sentinel (see PairedDeviceStore.revoke) and matches nothing.78     */79    fun isRevoked(deviceId: String, longTermPublicKeyHex: String? = null): Boolean {80        val key = longTermPublicKeyHex?.lowercase()?.takeIf { it != NO_KEY_SENTINEL }81        return listRevocations().any {82            it.deviceId == deviceId || (key != null && it.longTermPublicKeyHex.lowercase() == key)83        }84    }8586    /** Only a direct, SAS-confirmed re-pair may lift a terminal revocation. */87    fun clearRevocation(deviceId: String) {}88}8990fun buildSignedDeviceManifest(91    issuerDeviceId: String,92    devices: List<ManifestDeviceEntry>,93    signingPrivateKey: Ed25519PrivateKeyParameters,94    nowMs: Long = System.currentTimeMillis(),95    revoked: List<DeviceRevocation> = emptyList(),96): SignedDeviceManifest {97    require(issuerDeviceId.isNotBlank()) { "issuerDeviceId is required" }98    val issuerKeyHex = pubkeyToHex(signingPrivateKey.generatePublicKey().encoded)99    val body = DeviceManifestBody(100        manifestVersion = DEVICE_MANIFEST_VERSION,101        issuerDeviceId = issuerDeviceId,102        issuedAt = nowMs,103        devices = devices.map { normaliseManifestEntry(it) ?: it },104        revoked = revoked.map { record ->105            // A forwarded revocation is an immutable issuer statement. Preserve106            // its original issuer, key, and signature; only sign locally-created107            // records that have not been signed yet.108            if (record.signatureHex.isNotBlank()) {109                record110            } else {111                signDeviceRevocation(112                    record.copy(issuerDeviceId = issuerDeviceId, issuerSigningKeyHex = issuerKeyHex),113                    signingPrivateKey,114                )115            }116        },117    )118    val signature = signEd25519(signingPrivateKey, canonicalDeviceManifestBody(body).toByteArray(Charsets.UTF_8))119    return SignedDeviceManifest(body, pubkeyToHex(signature))120}121122/** Sign the immutable record, excluding its signature field from canonical bytes. */123fun signDeviceRevocation(124    record: DeviceRevocation,125    signingPrivateKey: Ed25519PrivateKeyParameters,126): DeviceRevocation {127    val keyHex = pubkeyToHex(signingPrivateKey.generatePublicKey().encoded)128    val unsigned = record.copy(129        issuerSigningKeyHex = keyHex,130        signatureHex = "",131    )132    val signature = signEd25519(133        signingPrivateKey,134        canonicalDeviceRevocation(unsigned).toByteArray(Charsets.UTF_8),135    )136    return unsigned.copy(signatureHex = pubkeyToHex(signature))137}138139fun canonicalDeviceRevocation(record: DeviceRevocation): String =140    canonicalise(141        mapOf(142            "deviceId" to record.deviceId,143            "issuerDeviceId" to record.issuerDeviceId,144            "issuerSigningKeyHex" to record.issuerSigningKeyHex.lowercase(),145            "longTermPublicKeyHex" to record.longTermPublicKeyHex.lowercase(),146            "revokedAt" to record.revokedAt,147            "revokedByDeviceId" to record.revokedByDeviceId,148        ),149    )150151fun verifyDeviceRevocation(record: DeviceRevocation, issuerSigningPublicKey: ByteArray): Boolean {152    if (!isHex(record.signatureHex, 128)) return false153    val signature = runCatching { hexToBytes(record.signatureHex) }.getOrNull() ?: return false154    return verifyEd25519(155        issuerSigningPublicKey,156        canonicalDeviceRevocation(record.copy(signatureHex = "")).toByteArray(Charsets.UTF_8),157        signature,158    )159}160161/**162 * A relayed revocation counts only when the key it names is one the receiver163 * already trusts for `revokedByDeviceId` — that device's current signing key or164 * an entry in its immutable known-key history. An unresolvable issuer fails165 * closed: the manifest is rejected rather than the record being skipped, so a166 * dropped history entry can never silently un-revoke a device.167 */168private fun isAuthorisedRevocation(169    record: DeviceRevocation,170    resolveIssuerSigningKeys: (String) -> Set<String>,171): Boolean {172    val statedKey = record.issuerSigningKeyHex.lowercase()173    val trusted = resolveIssuerSigningKeys(record.revokedByDeviceId).map { it.lowercase() }174    if (statedKey !in trusted) return false175    return verifyDeviceRevocation(record, hexToPubkey(statedKey))176}177178fun verifyDeviceManifest(179    manifest: SignedDeviceManifest,180    issuerSigningPublicKey: ByteArray,181    resolveIssuerSigningKeys: (String) -> Set<String>,182    nowMs: Long = System.currentTimeMillis(),183    freshnessMs: Long = DEVICE_MANIFEST_FRESHNESS_MS,184): DeviceManifestBody? {185    val body = manifest.body186    if (body.manifestVersion != DEVICE_MANIFEST_VERSION) return null187    // Two-sided bounds — avoids `abs(...) > window`, which overflows for188    // `Long.MIN_VALUE` and lets a peer-presented timestamp bypass the189    // freshness gate. Reject negative `issuedAt` outright so the bounds190    // arithmetic can't be steered into a wrap-around by the manifest.191    if (body.issuedAt < 0L) return null192    if (body.issuedAt < nowMs - freshnessMs || body.issuedAt > nowMs + freshnessMs) return null193    if (body.issuerDeviceId.isBlank() || body.issuerDeviceId.length > MAX_MANIFEST_STRING) return null194    if (body.devices.size > MAX_MANIFEST_DEVICES) return null195    if (body.revoked.size > MAX_MANIFEST_REVOCATIONS) return null196    // Validate every entry before the normalised return mapping below. Without197    // this guard, malformed but correctly signed manifests reached `!!` and198    // crashed the sync path instead of being rejected.199    if (body.devices.any { normaliseManifestEntry(it) == null }) return null200    if (!isHex(manifest.signatureHex, 128)) return null201    if (!body.revoked.all { isValidRevocation(it) }) return null202    val signature = runCatching { hexToBytes(manifest.signatureHex) }.getOrNull() ?: return null203    val canonical = canonicalDeviceManifestBody(body).toByteArray(Charsets.UTF_8)204    if (!verifyEd25519(issuerSigningPublicKey, canonical, signature)) return null205    // Forwarded tombstones retain the original issuer's immutable signature.206    // The enclosing manifest signature authenticates the forwarder only, so the207    // revocation's own issuer key MUST be one the receiver already knows for208    // `revokedByDeviceId` — never the key carried inside the record. Trusting209    // the record's own claim would let any admitted peer that can issue a210    // manifest eject any third device.211    if (!body.revoked.all { record -> isAuthorisedRevocation(record, resolveIssuerSigningKeys) }) return null212    // Return entries with the display name capped so every consumer (registry213    // upserts, pending-vouch queue, key-rotation alerts) stores the bounded214    // name. The signature above was verified against the raw body.215    return body.copy(devices = body.devices.map { normaliseManifestEntry(it)!! })216}217218fun canonicalDeviceManifestBody(body: DeviceManifestBody): String =219    canonicalise(220        mapOf(221            "devices" to body.devices.map { manifestEntryMap(it) },222            "issuedAt" to body.issuedAt,223            "issuerDeviceId" to body.issuerDeviceId,224            "manifestVersion" to body.manifestVersion,225            "revoked" to body.revoked.map { revocationMap(it) },226        ),227    )228229fun PairedDevice.toManifestEntry(): ManifestDeviceEntry? {230    val id = deviceId.takeIf { it.isNotBlank() } ?: return null231    val name = deviceName?.takeIf { it.isNotBlank() }?.let(::capDeviceName) ?: return null232    val type = deviceType?.takeIf { it in setOf("extension", "android", "ios") } ?: return null233    val longTerm = longTermPublicKeyHex?.lowercase()?.takeIf { isHex(it, 64) } ?: return null234    val signing = signingPublicKeyHex?.lowercase()?.takeIf { isHex(it, 64) } ?: return null235    return ManifestDeviceEntry(236        deviceId = id,237        deviceName = name,238        deviceType = type,239        longTermPublicKeyHex = longTerm,240        signingPublicKeyHex = signing,241        wsPort = wsPort,242        relayUrl = relayUrl,243        pairedAt = pairedAt,244        vouchDepth = 0,245    )246}247248private fun normaliseManifestEntry(entry: ManifestDeviceEntry): ManifestDeviceEntry? {249    if (entry.deviceId.isBlank() || entry.deviceName.isBlank()) return null250    if (entry.deviceId.length > MAX_MANIFEST_STRING) return null251    if (entry.deviceType !in setOf("extension", "android", "ios")) return null252    if (!isHex(entry.longTermPublicKeyHex, 64) || !isHex(entry.signingPublicKeyHex, 64)) return null253    if (entry.wsPort != null && entry.wsPort !in 1..65_535) return null254    if (entry.pairedAt < 0L || entry.vouchDepth !in 0..MAX_VOUCH_DEPTH) return null255    if (256        entry.relayUrl != null && (257            entry.relayUrl.length > MAX_MANIFEST_STRING ||258            runCatching { Rendezvous.normalizeRelayUrl(entry.relayUrl) }.isFailure259        )260    ) return null261    return entry.copy(262        deviceName = capDeviceName(entry.deviceName),263        longTermPublicKeyHex = entry.longTermPublicKeyHex.lowercase(),264        signingPublicKeyHex = entry.signingPublicKeyHex.lowercase(),265    )266}267268private fun normaliseRevocation(r: DeviceRevocation): DeviceRevocation =269    r.copy(longTermPublicKeyHex = r.longTermPublicKeyHex.lowercase())270271private fun isValidRevocation(r: DeviceRevocation): Boolean =272    r.deviceId.isNotBlank() && r.deviceId.length <= MAX_MANIFEST_STRING &&273        isHex(r.longTermPublicKeyHex.lowercase(), 64) &&274        r.revokedByDeviceId.isNotBlank() && r.revokedByDeviceId.length <= MAX_MANIFEST_STRING &&275        r.issuerDeviceId.isNotBlank() && r.issuerDeviceId.length <= MAX_MANIFEST_STRING &&276        isHex(r.issuerSigningKeyHex.lowercase(), 64) &&277        isHex(r.signatureHex, 128) &&278        r.revokedAt >= 0L279 280281private fun revocationMap(r: DeviceRevocation): Map<String, Any> = linkedMapOf(282    "deviceId" to r.deviceId,283    "issuerDeviceId" to r.issuerDeviceId,284    "issuerSigningKeyHex" to r.issuerSigningKeyHex.lowercase(),285    "longTermPublicKeyHex" to r.longTermPublicKeyHex.lowercase(),286    "revokedAt" to r.revokedAt,287    "revokedByDeviceId" to r.revokedByDeviceId,288    "signatureHex" to r.signatureHex.lowercase(),289)290291private fun manifestEntryMap(entry: ManifestDeviceEntry): Map<String, Any> {292    val normalised = normaliseManifestEntry(entry) ?: entry293    val map = linkedMapOf<String, Any>(294        "deviceId" to normalised.deviceId,295        "deviceName" to normalised.deviceName,296        "deviceType" to normalised.deviceType,297        "longTermPublicKeyHex" to normalised.longTermPublicKeyHex.lowercase(),298        "pairedAt" to normalised.pairedAt,299        "signingPublicKeyHex" to normalised.signingPublicKeyHex.lowercase(),300        "vouchDepth" to normalised.vouchDepth,301    )302    normalised.wsPort?.let { map["wsPort"] = it }303    normalised.relayUrl?.let { map["relayUrl"] = it }304    return map305}306307private fun canonicalise(value: Any?): String = when (value) {308    null -> "null"309    is Number -> {310        val d = value.toDouble()311        require(d.isFinite()) { "non-finite number" }312        if (d % 1.0 == 0.0) value.toLong().toString() else value.toString()313    }314    is String -> Json.encodeToString(String.serializer(), value)315    is Boolean -> if (value) "true" else "false"316    is List<*> -> value.joinToString(prefix = "[", postfix = "]", separator = ",") { canonicalise(it) }317    is Map<*, *> -> value.entries318        .map { (k, v) -> k.toString() to v }319        .sortedBy { it.first }320        .joinToString(prefix = "{", postfix = "}", separator = ",") { (k, v) ->321            Json.encodeToString(String.serializer(), k) + ":" + canonicalise(v)322        }323    else -> error("cannot canonicalise ${value::class.simpleName}")324}325326private fun isHex(value: String, length: Int): Boolean =327    value.length == length && value.all { it in '0'..'9' || it in 'a'..'f' }