DeviceManifestSupport.kt

11.1 KB · raw

1package com.peachpasswords.sync23import kotlinx.serialization.builtins.serializer4import kotlinx.serialization.json.Json5import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters67/** 0x04 adds signed vouch depth to each introduced peer edge. */8const val DEVICE_MANIFEST_VERSION = 0x049const 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    /** Commit a complete staged manifest as one logical registry mutation. */59    fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean6061    /** Returns the ids that were not already revoked. */62    fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> = emptyList()6364    /**65     * True when either the id or the long-term key is under a terminal66     * revocation. `deviceId` is a self-asserted string in a manifest, so67     * keying terminality on it alone is bypassed by re-vouching a revoked68     * device's key under a fresh id. The key is what a revoked device still69     * holds, so it is what terminality has to follow. `0`×64 is the "no key was70     * ever stored" sentinel (see PairedDeviceStore.revoke) and matches nothing.71     */72    fun isRevoked(deviceId: String, longTermPublicKeyHex: String? = null): Boolean {73        val key = longTermPublicKeyHex?.lowercase()?.takeIf { it != NO_KEY_SENTINEL }74        return listRevocations().any {75            it.deviceId == deviceId || (key != null && it.longTermPublicKeyHex.lowercase() == key)76        }77    }7879    /** Only a direct, SAS-confirmed re-pair may lift a terminal revocation. */80    fun clearRevocation(deviceId: String) {}81}8283fun buildSignedDeviceManifest(84    issuerDeviceId: String,85    devices: List<ManifestDeviceEntry>,86    signingPrivateKey: Ed25519PrivateKeyParameters,87    nowMs: Long = System.currentTimeMillis(),88    revoked: List<DeviceRevocation> = emptyList(),89): SignedDeviceManifest {90    require(issuerDeviceId.isNotBlank()) { "issuerDeviceId is required" }91    val body = DeviceManifestBody(92        manifestVersion = DEVICE_MANIFEST_VERSION,93        issuerDeviceId = issuerDeviceId,94        issuedAt = nowMs,95        // Normalise valid entries but keep invalid ones too — verifyDeviceManifest96        // is the gate that detects malformed input (M-09: silent drop would let97        // a caller believe they sent a valid manifest).98        devices = devices.map { normaliseManifestEntry(it) ?: it },99        revoked = revoked.map(::normaliseRevocation),100    )101    val signature = signEd25519(signingPrivateKey, canonicalDeviceManifestBody(body).toByteArray(Charsets.UTF_8))102    return SignedDeviceManifest(body, pubkeyToHex(signature))103}104105fun verifyDeviceManifest(106    manifest: SignedDeviceManifest,107    issuerSigningPublicKey: ByteArray,108    nowMs: Long = System.currentTimeMillis(),109    freshnessMs: Long = DEVICE_MANIFEST_FRESHNESS_MS,110): DeviceManifestBody? {111    val body = manifest.body112    if (body.manifestVersion != DEVICE_MANIFEST_VERSION) return null113    // Two-sided bounds — avoids `abs(...) > window`, which overflows for114    // `Long.MIN_VALUE` and lets a peer-presented timestamp bypass the115    // freshness gate. Reject negative `issuedAt` outright so the bounds116    // arithmetic can't be steered into a wrap-around by the manifest.117    if (body.issuedAt < 0L) return null118    if (body.issuedAt < nowMs - freshnessMs || body.issuedAt > nowMs + freshnessMs) return null119    if (body.issuerDeviceId.isBlank() || body.issuerDeviceId.length > MAX_MANIFEST_STRING) return null120    if (body.devices.size > MAX_MANIFEST_DEVICES) return null121    if (body.revoked.size > MAX_MANIFEST_REVOCATIONS) return null122    if (!isHex(manifest.signatureHex, 128)) return null123    if (!body.devices.all { normaliseManifestEntry(it) != null }) return null124    if (!body.revoked.all { isValidRevocation(it) }) return null125    val signature = runCatching { hexToBytes(manifest.signatureHex) }.getOrNull() ?: return null126    val canonical = canonicalDeviceManifestBody(body).toByteArray(Charsets.UTF_8)127    if (!verifyEd25519(issuerSigningPublicKey, canonical, signature)) return null128    // Return entries with the display name capped so every consumer (registry129    // upserts, pending-vouch queue, key-rotation alerts) stores the bounded130    // name. The signature above was verified against the raw body.131    return body.copy(devices = body.devices.map { normaliseManifestEntry(it)!! })132}133134fun canonicalDeviceManifestBody(body: DeviceManifestBody): String =135    canonicalise(136        mapOf(137            "devices" to body.devices.map { manifestEntryMap(it) },138            "issuedAt" to body.issuedAt,139            "issuerDeviceId" to body.issuerDeviceId,140            "manifestVersion" to body.manifestVersion,141            "revoked" to body.revoked.map { revocationMap(it) },142        ),143    )144145fun PairedDevice.toManifestEntry(): ManifestDeviceEntry? {146    val id = deviceId.takeIf { it.isNotBlank() } ?: return null147    val name = deviceName?.takeIf { it.isNotBlank() }?.let(::capDeviceName) ?: return null148    val type = deviceType?.takeIf { it in setOf("extension", "android", "ios") } ?: return null149    val longTerm = longTermPublicKeyHex?.lowercase()?.takeIf { isHex(it, 64) } ?: return null150    val signing = signingPublicKeyHex?.lowercase()?.takeIf { isHex(it, 64) } ?: return null151    return ManifestDeviceEntry(152        deviceId = id,153        deviceName = name,154        deviceType = type,155        longTermPublicKeyHex = longTerm,156        signingPublicKeyHex = signing,157        wsPort = wsPort,158        relayUrl = relayUrl,159        pairedAt = pairedAt,160        vouchDepth = 0,161    )162}163164private fun normaliseManifestEntry(entry: ManifestDeviceEntry): ManifestDeviceEntry? {165    if (entry.deviceId.isBlank() || entry.deviceName.isBlank()) return null166    // Bound string fields — a peer could otherwise send multi-megabyte strings167    // that pass the format checks and bloat the canonical signature input.168    // deviceName is capped (not rejected) at MAX_DEVICE_NAME_CHARS, matching169    // the browser, so a long-but-honest name still syncs.170    if (entry.deviceId.length > MAX_MANIFEST_STRING) return null171    if (entry.deviceType !in setOf("extension", "android", "ios")) return null172    if (!isHex(entry.longTermPublicKeyHex, 64) || !isHex(entry.signingPublicKeyHex, 64)) return null173    if (entry.wsPort != null && entry.wsPort !in 1..65_535) return null174    if (entry.pairedAt < 0L || entry.vouchDepth !in 0..MAX_VOUCH_DEPTH) return null175    if (176        entry.relayUrl != null && (177            entry.relayUrl.length > MAX_MANIFEST_STRING ||178            runCatching { Rendezvous.normalizeRelayUrl(entry.relayUrl) }.isFailure179        )180    ) return null181    return entry.copy(182        deviceName = capDeviceName(entry.deviceName),183        longTermPublicKeyHex = entry.longTermPublicKeyHex.lowercase(),184        signingPublicKeyHex = entry.signingPublicKeyHex.lowercase(),185    )186}187188private fun normaliseRevocation(r: DeviceRevocation): DeviceRevocation =189    r.copy(longTermPublicKeyHex = r.longTermPublicKeyHex.lowercase())190191private fun isValidRevocation(r: DeviceRevocation): Boolean =192    r.deviceId.isNotBlank() && r.deviceId.length <= MAX_MANIFEST_STRING &&193        isHex(r.longTermPublicKeyHex.lowercase(), 64) &&194        r.revokedByDeviceId.isNotBlank() && r.revokedByDeviceId.length <= MAX_MANIFEST_STRING &&195        r.revokedAt >= 0L196197private fun revocationMap(r: DeviceRevocation): Map<String, Any> = linkedMapOf(198    "deviceId" to r.deviceId,199    "longTermPublicKeyHex" to r.longTermPublicKeyHex.lowercase(),200    "revokedAt" to r.revokedAt,201    "revokedByDeviceId" to r.revokedByDeviceId,202)203204private fun manifestEntryMap(entry: ManifestDeviceEntry): Map<String, Any> {205    val normalised = normaliseManifestEntry(entry) ?: entry206    val map = linkedMapOf<String, Any>(207        "deviceId" to normalised.deviceId,208        "deviceName" to normalised.deviceName,209        "deviceType" to normalised.deviceType,210        "longTermPublicKeyHex" to normalised.longTermPublicKeyHex.lowercase(),211        "pairedAt" to normalised.pairedAt,212        "signingPublicKeyHex" to normalised.signingPublicKeyHex.lowercase(),213        "vouchDepth" to normalised.vouchDepth,214    )215    normalised.wsPort?.let { map["wsPort"] = it }216    normalised.relayUrl?.let { map["relayUrl"] = it }217    return map218}219220private fun canonicalise(value: Any?): String = when (value) {221    null -> "null"222    is Number -> {223        val d = value.toDouble()224        require(d.isFinite()) { "non-finite number" }225        if (d % 1.0 == 0.0) value.toLong().toString() else value.toString()226    }227    is String -> Json.encodeToString(String.serializer(), value)228    is Boolean -> if (value) "true" else "false"229    is List<*> -> value.joinToString(prefix = "[", postfix = "]", separator = ",") { canonicalise(it) }230    is Map<*, *> -> value.entries231        .map { (k, v) -> k.toString() to v }232        .sortedBy { it.first }233        .joinToString(prefix = "{", postfix = "}", separator = ",") { (k, v) ->234            Json.encodeToString(String.serializer(), k) + ":" + canonicalise(v)235        }236    else -> error("cannot canonicalise ${value::class.simpleName}")237}238239private fun isHex(value: String, length: Int): Boolean =240    value.length == length && value.all { it in '0'..'9' || it in 'a'..'f' }