DeviceManifestSupport.kt

15.7 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 = 25620internal const val MAX_MANIFEST_REVOCATIONS = 50021internal 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"3536data class DeviceManifestIssuerBinding(37    val deviceId: String,38    val longTermPublicKeyHex: String,39    val signingPublicKeyHex: String,40)4142/**43 * Fully staged membership change. Implementations must linearize the whole44 * batch; callers hold the vault session epoch fence while invoking it, so a45 * lock/re-unlock cannot observe or leave behind a half-applied manifest.46 */47data class DeviceManifestRegistryBatch(48    val incomingRevocations: List<DeviceRevocation>,49    val removals: Set<String>,50    val upserts: List<PairedDevice>,51    val issuerSigningKeys: Map<String, Set<String>> = emptyMap(),52    val authenticatedIssuer: DeviceManifestIssuerBinding,53    val expectedSnapshot: DeviceManifestRegistrySnapshot,54)5556data class DeviceManifestRegistrySnapshot(57    val devices: List<PairedDevice>,58    val revocations: List<DeviceRevocation>,59    val issuerSigningKeys: Map<String, Set<String>>,60)6162interface PairedDeviceRegistry {63    fun getAll(): List<PairedDevice>64    fun get(id: String): PairedDevice?65    fun getByPubkey(pubkeyHex: String): PairedDevice? =66        getAll().firstOrNull {67            it.longTermPublicKeyHex?.let { key -> CryptoCompare.hex(key, pubkeyHex) } == true68        }69    fun upsert(device: PairedDevice)70    fun remove(deviceId: String) {}71    fun listRevocations(): List<DeviceRevocation> = emptyList()7273    /**74     * Immutable issuer signing-key history. Implementations must append only;75     * the default keeps lightweight test registries source-compatible.76     */77    fun issuerSigningKeys(issuerDeviceId: String): Set<String> = emptySet()78    fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean = true7980    /** Production stores capture all fields atomically; the fallback uses existing reads. */81    fun manifestSnapshot(requestedIssuerIds: Set<String>): DeviceManifestRegistrySnapshot {82        val devices = getAll()83        val revocations = listRevocations()84        val issuers = requestedIssuerIds + devices.map { it.deviceId } + revocations.map { it.revokedByDeviceId }85        return DeviceManifestRegistrySnapshot(86            devices,87            revocations,88            issuers.associateWith { issuerSigningKeys(it).toSet() },89        )90    }9192    /** Commit a complete staged manifest as one logical registry mutation. */93    fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean9495    /** Returns the ids that were not already revoked. */96    fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> = emptyList()9798    /**99     * True when either the id or the long-term key is under a terminal100     * revocation. `deviceId` is a self-asserted string in a manifest, so101     * keying terminality on it alone is bypassed by re-vouching a revoked102     * device's key under a fresh id. The key is what a revoked device still103     * holds, so it is what terminality has to follow. `0`×64 is the "no key was104     * ever stored" sentinel (see PairedDeviceStore.revoke) and matches nothing.105     */106    fun isRevoked(deviceId: String, longTermPublicKeyHex: String? = null): Boolean {107        val key = longTermPublicKeyHex?.lowercase()?.takeIf { it != NO_KEY_SENTINEL }108        return listRevocations().any {109            it.deviceId == deviceId || (key != null && it.longTermPublicKeyHex.lowercase() == key)110        }111    }112113    /** Only a direct, SAS-confirmed re-pair may lift a terminal revocation. */114    fun clearRevocation(deviceId: String) {}115}116117fun buildSignedDeviceManifest(118    issuerDeviceId: String,119    devices: List<ManifestDeviceEntry>,120    signingPrivateKey: Ed25519PrivateKeyParameters,121    nowMs: Long = System.currentTimeMillis(),122    revoked: List<DeviceRevocation> = emptyList(),123): SignedDeviceManifest {124    require(issuerDeviceId.isNotBlank()) { "issuerDeviceId is required" }125    val body = DeviceManifestBody(126        manifestVersion = DEVICE_MANIFEST_VERSION,127        issuerDeviceId = issuerDeviceId,128        issuedAt = nowMs,129        devices = devices.map { normaliseManifestEntry(it) ?: it },130        revoked = revoked.map { record ->131            // A forwarded revocation is an immutable issuer statement. Preserve132            // its original issuer and signature; only sign locally-created133            // records that have not been signed yet.134            if (record.signatureHex.isNotBlank()) record else signDeviceRevocation(record, signingPrivateKey)135        },136    )137    val signature = signEd25519(signingPrivateKey, canonicalDeviceManifestBody(body).toByteArray(Charsets.UTF_8))138    return SignedDeviceManifest(body, pubkeyToHex(signature))139}140141/** Sign the immutable record, excluding its signature field from canonical bytes. */142fun signDeviceRevocation(143    record: DeviceRevocation,144    signingPrivateKey: Ed25519PrivateKeyParameters,145): DeviceRevocation {146    val unsigned = record.copy(signatureHex = "")147    val signature = signEd25519(148        signingPrivateKey,149        canonicalDeviceRevocation(unsigned).toByteArray(Charsets.UTF_8),150    )151    return unsigned.copy(signatureHex = pubkeyToHex(signature))152}153154/** The exact bytes an issuer signs; identical in Browser and Android. */155fun canonicalDeviceRevocation(record: DeviceRevocation): String =156    canonicalise(157        mapOf(158            "deviceId" to record.deviceId,159            "longTermPublicKeyHex" to record.longTermPublicKeyHex.lowercase(),160            "recordVersion" to record.recordVersion,161            "revokedAt" to record.revokedAt,162            "revokedByDeviceId" to record.revokedByDeviceId,163        ),164    )165166fun verifyDeviceRevocation(record: DeviceRevocation, issuerSigningPublicKey: ByteArray): Boolean {167    if (!isHex(record.signatureHex, 128)) return false168    val signature = runCatching { hexToBytes(record.signatureHex) }.getOrNull() ?: return false169    return verifyEd25519(170        issuerSigningPublicKey,171        canonicalDeviceRevocation(record.copy(signatureHex = "")).toByteArray(Charsets.UTF_8),172        signature,173    )174}175176/**177 * A relayed revocation counts only when its signature verifies under a key the178 * receiver already trusts for `revokedByDeviceId` — that device's current179 * signing key or an entry in its immutable known-key history. The record names180 * no key of its own, so a relaying peer cannot authorise anything by supplying181 * one.182 *183 * An unresolvable issuer fails closed: the manifest is rejected rather than the184 * record being skipped, so a dropped history entry can never silently185 * un-revoke a device.186 */187private fun isAuthorisedRevocation(188    record: DeviceRevocation,189    resolveIssuerSigningKeys: (String) -> Set<String>,190): Boolean {191    val signature = runCatching { hexToBytes(record.signatureHex) }.getOrNull() ?: return false192    val payload = canonicalDeviceRevocation(record.copy(signatureHex = "")).toByteArray(Charsets.UTF_8)193    val trusted = resolveIssuerSigningKeys(record.revokedByDeviceId)194    if (trusted.isEmpty()) return false195    return trusted.any { key ->196        val hex = key.lowercase()197        isHex(hex, 64) && verifyEd25519(hexToPubkey(hex), payload, signature)198    }199}200201fun verifyDeviceManifest(202    manifest: SignedDeviceManifest,203    issuerSigningPublicKey: ByteArray,204    resolveIssuerSigningKeys: (String) -> Set<String>,205    nowMs: Long = System.currentTimeMillis(),206    freshnessMs: Long = DEVICE_MANIFEST_FRESHNESS_MS,207): DeviceManifestBody? {208    val body = manifest.body209    if (body.manifestVersion != DEVICE_MANIFEST_VERSION) return null210    // Two-sided bounds — avoids `abs(...) > window`, which overflows for211    // `Long.MIN_VALUE` and lets a peer-presented timestamp bypass the212    // freshness gate. Reject negative `issuedAt` outright so the bounds213    // arithmetic can't be steered into a wrap-around by the manifest.214    if (body.issuedAt < 0L) return null215    if (body.issuedAt < nowMs - freshnessMs || body.issuedAt > nowMs + freshnessMs) return null216    if (body.issuerDeviceId.isBlank() || body.issuerDeviceId.length > MAX_MANIFEST_STRING) return null217    if (body.devices.size > MAX_MANIFEST_DEVICES) return null218    if (body.revoked.size > MAX_MANIFEST_REVOCATIONS) return null219    // Validate every entry before the normalised return mapping below. Without220    // this guard, malformed but correctly signed manifests reached `!!` and221    // crashed the sync path instead of being rejected.222    if (body.devices.any { normaliseManifestEntry(it) == null }) return null223    if (!isHex(manifest.signatureHex, 128)) return null224    if (!body.revoked.all { isValidRevocation(it) }) return null225    val signature = runCatching { hexToBytes(manifest.signatureHex) }.getOrNull() ?: return null226    val canonical = canonicalDeviceManifestBody(body).toByteArray(Charsets.UTF_8)227    if (!verifyEd25519(issuerSigningPublicKey, canonical, signature)) return null228    // Forwarded tombstones retain the original issuer's immutable signature.229    // The enclosing manifest signature authenticates the forwarder only, so the230    // revocation's own issuer key MUST be one the receiver already knows for231    // `revokedByDeviceId` — never the key carried inside the record. Trusting232    // the record's own claim would let any admitted peer that can issue a233    // manifest eject any third device.234    if (!body.revoked.all { record -> isAuthorisedRevocation(record, resolveIssuerSigningKeys) }) return null235    // Return entries with the display name capped so every consumer (registry236    // upserts, pending-vouch queue, key-rotation alerts) stores the bounded237    // name. The signature above was verified against the raw body.238    return body.copy(devices = body.devices.map { normaliseManifestEntry(it)!! })239}240241fun canonicalDeviceManifestBody(body: DeviceManifestBody): String =242    canonicalise(243        mapOf(244            "devices" to body.devices.map { manifestEntryMap(it) },245            "issuedAt" to body.issuedAt,246            "issuerDeviceId" to body.issuerDeviceId,247            "manifestVersion" to body.manifestVersion,248            "revoked" to body.revoked.map { revocationMap(it) },249        ),250    )251252fun PairedDevice.toManifestEntry(): ManifestDeviceEntry? {253    val id = deviceId.takeIf { it.isNotBlank() } ?: return null254    val name = deviceName?.takeIf { it.isNotBlank() }?.let(::capDeviceName) ?: return null255    val type = deviceType?.takeIf { it in setOf("extension", "android", "ios") } ?: return null256    val longTerm = longTermPublicKeyHex?.lowercase()?.takeIf { isHex(it, 64) } ?: return null257    val signing = signingPublicKeyHex?.lowercase()?.takeIf { isHex(it, 64) } ?: return null258    return ManifestDeviceEntry(259        deviceId = id,260        deviceName = name,261        deviceType = type,262        longTermPublicKeyHex = longTerm,263        signingPublicKeyHex = signing,264        wsPort = wsPort,265        relayUrl = relayUrl,266        pairedAt = pairedAt,267        vouchDepth = 0,268    )269}270271private fun normaliseManifestEntry(entry: ManifestDeviceEntry): ManifestDeviceEntry? {272    if (entry.deviceId.isBlank() || entry.deviceName.isBlank()) return null273    if (entry.deviceId.length > MAX_MANIFEST_STRING) return null274    if (entry.deviceType !in setOf("extension", "android", "ios")) return null275    if (!isHex(entry.longTermPublicKeyHex, 64) || !isHex(entry.signingPublicKeyHex, 64)) return null276    if (entry.wsPort != null && entry.wsPort !in 1..65_535) return null277    if (entry.pairedAt < 0L || entry.vouchDepth !in 0..MAX_VOUCH_DEPTH) return null278    if (279        entry.relayUrl != null && (280            entry.relayUrl.length > MAX_MANIFEST_STRING ||281            runCatching { Rendezvous.normalizeRelayUrl(entry.relayUrl) }.isFailure282        )283    ) return null284    return entry.copy(285        deviceName = capDeviceName(entry.deviceName),286        longTermPublicKeyHex = entry.longTermPublicKeyHex.lowercase(),287        signingPublicKeyHex = entry.signingPublicKeyHex.lowercase(),288    )289}290291private fun normaliseRevocation(r: DeviceRevocation): DeviceRevocation =292    r.copy(longTermPublicKeyHex = r.longTermPublicKeyHex.lowercase())293294private fun isValidRevocation(r: DeviceRevocation): Boolean =295    r.recordVersion == DEVICE_REVOCATION_RECORD_VERSION &&296        r.deviceId.isNotBlank() && r.deviceId.length <= MAX_MANIFEST_STRING &&297        isHex(r.longTermPublicKeyHex.lowercase(), 64) &&298        r.revokedByDeviceId.isNotBlank() && r.revokedByDeviceId.length <= MAX_MANIFEST_STRING &&299        isHex(r.signatureHex, 128) &&300        r.revokedAt >= 0L301 302303private fun revocationMap(r: DeviceRevocation): Map<String, Any> = linkedMapOf(304    "deviceId" to r.deviceId,305    "longTermPublicKeyHex" to r.longTermPublicKeyHex.lowercase(),306    "recordVersion" to r.recordVersion,307    "revokedAt" to r.revokedAt,308    "revokedByDeviceId" to r.revokedByDeviceId,309    "signatureHex" to r.signatureHex.lowercase(),310)311312private fun manifestEntryMap(entry: ManifestDeviceEntry): Map<String, Any> {313    val normalised = normaliseManifestEntry(entry) ?: entry314    val map = linkedMapOf<String, Any>(315        "deviceId" to normalised.deviceId,316        "deviceName" to normalised.deviceName,317        "deviceType" to normalised.deviceType,318        "longTermPublicKeyHex" to normalised.longTermPublicKeyHex.lowercase(),319        "pairedAt" to normalised.pairedAt,320        "signingPublicKeyHex" to normalised.signingPublicKeyHex.lowercase(),321        "vouchDepth" to normalised.vouchDepth,322    )323    normalised.wsPort?.let { map["wsPort"] = it }324    normalised.relayUrl?.let { map["relayUrl"] = it }325    return map326}327328private fun canonicalise(value: Any?): String = when (value) {329    null -> "null"330    is Number -> {331        val d = value.toDouble()332        require(d.isFinite()) { "non-finite number" }333        if (d % 1.0 == 0.0) value.toLong().toString() else value.toString()334    }335    is String -> Json.encodeToString(String.serializer(), value)336    is Boolean -> if (value) "true" else "false"337    is List<*> -> value.joinToString(prefix = "[", postfix = "]", separator = ",") { canonicalise(it) }338    is Map<*, *> -> value.entries339        .map { (k, v) -> k.toString() to v }340        .sortedBy { it.first }341        .joinToString(prefix = "{", postfix = "}", separator = ",") { (k, v) ->342            Json.encodeToString(String.serializer(), k) + ":" + canonicalise(v)343        }344    else -> error("cannot canonicalise ${value::class.simpleName}")345}346347private fun isHex(value: String, length: Int): Boolean =348    value.length == length && value.all { it in '0'..'9' || it in 'a'..'f' }