1package com.peachpasswords.sync23import kotlinx.serialization.builtins.serializer4import kotlinx.serialization.json.Json5import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters678const val DEVICE_MANIFEST_VERSION = 0x059const val MAX_VOUCH_DEPTH = 310private const val DEVICE_MANIFEST_FRESHNESS_MS = 5 * 60_000L111213141516171819private const val MAX_MANIFEST_DEVICES = 25620private const val MAX_MANIFEST_REVOCATIONS = 50021private const val MAX_MANIFEST_STRING = 2562223242526272829internal const val MAX_DEVICE_NAME_CHARS = 64303132internal 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"35363738394041data 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 59606162 fun issuerSigningKeys(issuerDeviceId: String): Set<String> = emptySet()63 fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean = true6465 66 fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean6768 69 fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> = emptyList()7071 7273747576777879 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 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 106 107 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}121122123fun 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}160161fun verifyDeviceManifest(162 manifest: SignedDeviceManifest,163 issuerSigningPublicKey: ByteArray,164 nowMs: Long = System.currentTimeMillis(),165 freshnessMs: Long = DEVICE_MANIFEST_FRESHNESS_MS,166): DeviceManifestBody? {167 val body = manifest.body168 if (body.manifestVersion != DEVICE_MANIFEST_VERSION) return null169 170 171 172 173 if (body.issuedAt < 0L) return null174 if (body.issuedAt < nowMs - freshnessMs || body.issuedAt > nowMs + freshnessMs) return null175 if (body.issuerDeviceId.isBlank() || body.issuerDeviceId.length > MAX_MANIFEST_STRING) return null176 if (body.devices.size > MAX_MANIFEST_DEVICES) return null177 if (body.revoked.size > MAX_MANIFEST_REVOCATIONS) return null178 179 180 181 if (body.devices.any { normaliseManifestEntry(it) == null }) return null182 if (!isHex(manifest.signatureHex, 128)) return null183 if (!body.revoked.all { isValidRevocation(it) }) return null184 val signature = runCatching { hexToBytes(manifest.signatureHex) }.getOrNull() ?: return null185 val canonical = canonicalDeviceManifestBody(body).toByteArray(Charsets.UTF_8)186 if (!verifyEd25519(issuerSigningPublicKey, canonical, signature)) return null187 188 189 190 if (!body.revoked.all { record ->191 val recordKey = runCatching { hexToPubkey(record.issuerSigningKeyHex) }.getOrNull()192 ?: return@all false193 verifyDeviceRevocation(record, recordKey)194 }) return null195 196 197 198 return body.copy(devices = body.devices.map { normaliseManifestEntry(it)!! })199}200201fun canonicalDeviceManifestBody(body: DeviceManifestBody): String =202 canonicalise(203 mapOf(204 "devices" to body.devices.map { manifestEntryMap(it) },205 "issuedAt" to body.issuedAt,206 "issuerDeviceId" to body.issuerDeviceId,207 "manifestVersion" to body.manifestVersion,208 "revoked" to body.revoked.map { revocationMap(it) },209 ),210 )211212fun PairedDevice.toManifestEntry(): ManifestDeviceEntry? {213 val id = deviceId.takeIf { it.isNotBlank() } ?: return null214 val name = deviceName?.takeIf { it.isNotBlank() }?.let(::capDeviceName) ?: return null215 val type = deviceType?.takeIf { it in setOf("extension", "android", "ios") } ?: return null216 val longTerm = longTermPublicKeyHex?.lowercase()?.takeIf { isHex(it, 64) } ?: return null217 val signing = signingPublicKeyHex?.lowercase()?.takeIf { isHex(it, 64) } ?: return null218 return ManifestDeviceEntry(219 deviceId = id,220 deviceName = name,221 deviceType = type,222 longTermPublicKeyHex = longTerm,223 signingPublicKeyHex = signing,224 wsPort = wsPort,225 relayUrl = relayUrl,226 pairedAt = pairedAt,227 vouchDepth = 0,228 )229}230231private fun normaliseManifestEntry(entry: ManifestDeviceEntry): ManifestDeviceEntry? {232 if (entry.deviceId.isBlank() || entry.deviceName.isBlank()) return null233 if (entry.deviceId.length > MAX_MANIFEST_STRING) return null234 if (entry.deviceType !in setOf("extension", "android", "ios")) return null235 if (!isHex(entry.longTermPublicKeyHex, 64) || !isHex(entry.signingPublicKeyHex, 64)) return null236 if (entry.wsPort != null && entry.wsPort !in 1..65_535) return null237 if (entry.pairedAt < 0L || entry.vouchDepth !in 0..MAX_VOUCH_DEPTH) return null238 if (239 entry.relayUrl != null && (240 entry.relayUrl.length > MAX_MANIFEST_STRING ||241 runCatching { Rendezvous.normalizeRelayUrl(entry.relayUrl) }.isFailure242 )243 ) return null244 return entry.copy(245 deviceName = capDeviceName(entry.deviceName),246 longTermPublicKeyHex = entry.longTermPublicKeyHex.lowercase(),247 signingPublicKeyHex = entry.signingPublicKeyHex.lowercase(),248 )249}250251private fun normaliseRevocation(r: DeviceRevocation): DeviceRevocation =252 r.copy(longTermPublicKeyHex = r.longTermPublicKeyHex.lowercase())253254private fun isValidRevocation(r: DeviceRevocation): Boolean =255 r.deviceId.isNotBlank() && r.deviceId.length <= MAX_MANIFEST_STRING &&256 isHex(r.longTermPublicKeyHex.lowercase(), 64) &&257 r.revokedByDeviceId.isNotBlank() && r.revokedByDeviceId.length <= MAX_MANIFEST_STRING &&258 r.issuerDeviceId.isNotBlank() && r.issuerDeviceId.length <= MAX_MANIFEST_STRING &&259 isHex(r.issuerSigningKeyHex.lowercase(), 64) &&260 isHex(r.signatureHex, 128) &&261 r.revokedAt >= 0L262 263264private fun revocationMap(r: DeviceRevocation): Map<String, Any> = linkedMapOf(265 "deviceId" to r.deviceId,266 "issuerDeviceId" to r.issuerDeviceId,267 "issuerSigningKeyHex" to r.issuerSigningKeyHex.lowercase(),268 "longTermPublicKeyHex" to r.longTermPublicKeyHex.lowercase(),269 "revokedAt" to r.revokedAt,270 "revokedByDeviceId" to r.revokedByDeviceId,271 "signatureHex" to r.signatureHex.lowercase(),272)273274private fun manifestEntryMap(entry: ManifestDeviceEntry): Map<String, Any> {275 val normalised = normaliseManifestEntry(entry) ?: entry276 val map = linkedMapOf<String, Any>(277 "deviceId" to normalised.deviceId,278 "deviceName" to normalised.deviceName,279 "deviceType" to normalised.deviceType,280 "longTermPublicKeyHex" to normalised.longTermPublicKeyHex.lowercase(),281 "pairedAt" to normalised.pairedAt,282 "signingPublicKeyHex" to normalised.signingPublicKeyHex.lowercase(),283 "vouchDepth" to normalised.vouchDepth,284 )285 normalised.wsPort?.let { map["wsPort"] = it }286 normalised.relayUrl?.let { map["relayUrl"] = it }287 return map288}289290private fun canonicalise(value: Any?): String = when (value) {291 null -> "null"292 is Number -> {293 val d = value.toDouble()294 require(d.isFinite()) { "non-finite number" }295 if (d % 1.0 == 0.0) value.toLong().toString() else value.toString()296 }297 is String -> Json.encodeToString(String.serializer(), value)298 is Boolean -> if (value) "true" else "false"299 is List<*> -> value.joinToString(prefix = "[", postfix = "]", separator = ",") { canonicalise(it) }300 is Map<*, *> -> value.entries301 .map { (k, v) -> k.toString() to v }302 .sortedBy { it.first }303 .joinToString(prefix = "{", postfix = "}", separator = ",") { (k, v) ->304 Json.encodeToString(String.serializer(), k) + ":" + canonicalise(v)305 }306 else -> error("cannot canonicalise ${value::class.simpleName}")307}308309private fun isHex(value: String, length: Int): Boolean =310 value.length == length && value.all { it in '0'..'9' || it in 'a'..'f' }