perf(keygen): normalize software generateKey RTT to match TEE latency

Software-generated keys complete in ~4ms, real TEE averages 55-65ms
with a floor around 15ms. Detectors measure this RTT to distinguish
software from hardware paths. Gaussian delay sampling (mean=55ms,
σ=12ms, floor=15ms) brings total RTT into the expected range.
This commit is contained in:
Enginex0
2026-03-16 22:06:38 +01:00
parent 2a9ce5e0c8
commit 3749dec58b
@@ -317,6 +317,7 @@ class KeyMintSecurityLevelInterceptor(
keyId: KeyIdentifier, keyId: KeyIdentifier,
isAttestKeyRequest: Boolean, isAttestKeyRequest: Boolean,
): TransactionResult { ): TransactionResult {
val startNs = System.nanoTime()
keyDescriptor.nspace = secureRandom.nextLong() keyDescriptor.nspace = secureRandom.nextLong()
SystemLogger.info("Generating software key for ${keyDescriptor.alias}[${keyDescriptor.nspace}].") SystemLogger.info("Generating software key for ${keyDescriptor.alias}[${keyDescriptor.nspace}].")
@@ -350,6 +351,10 @@ class KeyMintSecurityLevelInterceptor(
isAttestationKey = isAttestKeyRequest, isAttestationKey = isAttestKeyRequest,
) )
val elapsedMs = (System.nanoTime() - startNs) / 1_000_000
val delayMs = sampleTeeLatencyMs() - elapsedMs
if (delayMs > 0) Thread.sleep(delayMs)
return InterceptorUtils.createTypedObjectReply(response.metadata) return InterceptorUtils.createTypedObjectReply(response.metadata)
} }
@@ -542,6 +547,9 @@ class KeyMintSecurityLevelInterceptor(
// Sliding window: max hardware keygen permits per UID within the burst window // Sliding window: max hardware keygen permits per UID within the burst window
private const val MAX_HW_KEYGEN_PER_WINDOW = 2 private const val MAX_HW_KEYGEN_PER_WINDOW = 2
private const val BURST_WINDOW_MS = 30_000L private const val BURST_WINDOW_MS = 30_000L
private const val TEE_LATENCY_MEAN_MS = 55.0
private const val TEE_LATENCY_STDDEV_MS = 12.0
private const val TEE_LATENCY_FLOOR_MS = 15L
private val uidHardwareKeygenCount = ConcurrentHashMap<Int, AtomicInteger>() private val uidHardwareKeygenCount = ConcurrentHashMap<Int, AtomicInteger>()
private val hardwareKeygenTxIds = ConcurrentHashMap.newKeySet<Long>() private val hardwareKeygenTxIds = ConcurrentHashMap.newKeySet<Long>()
@@ -570,6 +578,11 @@ class KeyMintSecurityLevelInterceptor(
} }
} }
private fun sampleTeeLatencyMs(): Long {
val sample = TEE_LATENCY_MEAN_MS + secureRandom.nextGaussian() * TEE_LATENCY_STDDEV_MS
return sample.toLong().coerceAtLeast(TEE_LATENCY_FLOOR_MS)
}
private val GENERATE_KEY_TRANSACTION = private val GENERATE_KEY_TRANSACTION =
InterceptorUtils.getTransactCode(IKeystoreSecurityLevel.Stub::class.java, "generateKey") InterceptorUtils.getTransactCode(IKeystoreSecurityLevel.Stub::class.java, "generateKey")
private val IMPORT_KEY_TRANSACTION = private val IMPORT_KEY_TRANSACTION =