This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-hardware-remote-attestation-standard

KMP Secure Hardware Key Remote Attestation Invariant Standard

Enforces strict cryptographic guarantees for Kotlin Multiplatform (KMP) remote attestation unifying Android KeyStore StrongBox and Apple Secure Enclave (DCAppAttestService). Requires strict separation of client-side key generation from attestation issuance, mandatory inclusion of server-provided cryptographically random nonces inside attestation extensions, and zero reliance on client-side certificate chain verification.

Prohibited Anti-Pattern: Client-Side Self-Attestation Validation and Replayable Local Nonce Generation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Secure Hardware Key Remote Attestation Invariant Standard - Enforces strict cryptographic guarantees for Kotlin Multiplatform (KMP) remote attestation unifying Android KeyStore StrongBox and Apple Secure Enclave (DCAppAttestService). Requires strict separation of client-side key generation from attestation issuance, mandatory inclusion of server-provided cryptographically random nonces inside attestation extensions, and zero reliance on client-side certificate chain verification.
globs: **/commonMain/**/attestation/**/*.kt, **/androidMain/**/crypto/**/*.kt, **/iosMain/**/crypto/**/*.kt, **/shared/**/security/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-hardware-remote-attestation-standard"
---

# KMP Secure Hardware Key Remote Attestation Invariant Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Client-Side Self-Attestation Validation and Replayable Local Nonce Generation

## System Constraints
You are a Principal Security Architect enforcing the KMP Secure Hardware Key Remote Attestation Standard. Mandate that private keys generated across Android StrongBox and iOS Secure Enclave are mathematically bound to non-exportable hardware keystores, attestations strictly embed fresh, single-use, cryptographically verified backend nonces, and all leaf/root X.509 or CBOR assertions are transmitted raw to the backend for authority validation without client-side parsing or validation.

## Strict Guidelines
- Engineers MUST ALWAYS require a server-generated, cryptographically random, ephemeral nonce (minimum 32 bytes) prior to calling hardware attestation APIs.
- Engineers MUST NOT verify X.509 certificate chains, Google Hardware Attestation Root certificates, or Apple App Attest roots locally within the mobile client application.
- Engineers MUST configure Android KeyGenParameterSpec with `setIsStrongBoxBacked(true)` and fail explicitly when StrongBoxUnavailableException is caught if strict hardware boundary is required.
- Engineers MUST bind Apple DCAppAttestService attestation challenges to a SHA-256 hash of the client data containing the server nonce and public key representation.
- Code SHOULD represent platform attestation payloads uniformly in commonMain as tagged sealed classes separating Android KeyStore X.509 leaf/intermediate chains from Apple CBOR attestation statements.
- Services MUST enforce server-side replay defense by tracking consumed nonces with tight time-to-live (TTL) expiration windows (<= 60 seconds).
- Components NEVER store or attempt to serialize private key material in common code or platform memory; operations must strictly execute inside isolated hardware boundaries.

## Bad vs Good Implementations
### Cross-Platform Hardware Key Attestation Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Generating nonces on-device exposes the attestation ceremony to replay attacks. Verifying root trust on the client creates a false sense of security that can be bypassed via runtime hooking (Frida/substrate). Additionally, failing to demand StrongBox enables keys to reside in lower-assurance TEEs or software keystores.
```kotlin
// ANTI-PATTERN: Client creates its own nonce, verifies its own root, and falls back insecurely
class HardwareKeyManager {
    fun generateAttestedKey(alias: String): ByteArray {
        // Insecure: Client-generated nonce allows replay attacks
        val localNonce = ByteArray(32).also { java.security.SecureRandom().nextBytes(it) }
        
        val keyPairGenerator = java.security.KeyPairGenerator.getInstance(
            android.security.keystore.KeyProperties.KEY_ALGORITHM_EC, 
            "AndroidKeyStore"
        )
        val spec = android.security.keystore.KeyGenParameterSpec.Builder(
            alias,
            android.security.keystore.KeyProperties.PURPOSE_SIGN
        ).run {
            // Missing StrongBox enforcement; soft fallback allowed
            setAttestationChallenge(localNonce)
            build()
        }
        keyPairGenerator.initialize(spec)
        keyPairGenerator.generateKeyPair()
        
        val keyStore = java.security.KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
        val chain = keyStore.getCertificateChain(alias)
        
        // Insecure: Client attempts to validate its own certificate chain
        if (!verifyChainLocally(chain)) {
            throw IllegalStateException("Invalid chain")
        }
        
        return chain[0].encoded
    }
    
    private fun verifyChainLocally(chain: Array<java.security.cert.Certificate>): Boolean = true
}
```

#### Production Standard (Correct)
> **Standard**: The production implementation enforces hardware-backed generation in a Dedicated Secure Element via `setIsStrongBoxBacked(true)`, binds attestation explicitly to a high-entropy server-provided nonce, and sends the raw certificates directly to the server without flawed client-side verification.
```kotlin
// PRODUCTION STANDARD: Common payload contract and rigid platform attestation enforcement
sealed interface RemoteAttestationPayload {
    data class AndroidStrongBox(
        val keyAlias: String,
        val certificateChainPem: List<String>,
        val serverNonce: ByteArray
    ) : RemoteAttestationPayload

    data class AppleAppAttest(
        val keyId: String,
        val attestationObjectBase64: String,
        val clientDataHash: ByteArray,
        val serverNonce: ByteArray
    ) : RemoteAttestationPayload
}

// Android Implementation
class AndroidStrongBoxAttestor(private val keyStore: java.security.KeyStore) {
    fun generateAndAttest(
        alias: String,
        serverNonce: ByteArray
    ): RemoteAttestationPayload.AndroidStrongBox {
        require(serverNonce.size >= 32) { "Nonce entropy insufficient; minimum 32 bytes required" }
        
        val kpg = java.security.KeyPairGenerator.getInstance(
            android.security.keystore.KeyProperties.KEY_ALGORITHM_EC,
            "AndroidKeyStore"
        )
        
        val spec = android.security.keystore.KeyGenParameterSpec.Builder(
            alias,
            android.security.keystore.KeyProperties.PURPOSE_SIGN or android.security.keystore.KeyProperties.PURPOSE_VERIFY
        )
            .setDigests(android.security.keystore.KeyProperties.DIGEST_SHA256)
            .setIsStrongBoxBacked(true) // Mandate Dedicated Secure Element (StrongBox)
            .setAttestationChallenge(serverNonce) // Bind ephemeral server challenge
            .build()
            
        kpg.initialize(spec)
        kpg.generateKeyPair()
        
        val certs = keyStore.getCertificateChain(alias) 
            ?: throw java.security.GeneralSecurityException("Attestation certificates missing")
            
        val pemChain = certs.map {
            java.util.Base64.getEncoder().encodeToString(it.encoded)
        }
        
        // Transmit raw unverified chain to backend for server-side evaluation
        return RemoteAttestationPayload.AndroidStrongBox(
            keyAlias = alias,
            certificateChainPem = pemChain,
            serverNonce = serverNonce
        )
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP Secure Hardware Key Remote Attestation Invariant Standard

KMP Secure Hardware Key Remote Attestation Invariant Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict cryptographic guarantees for Kotlin Multiplatform (KMP) remote attestation unifying Android KeyStore StrongBox and Apple Secure Enclave (DCAppAttestService). Requires strict separation of client-side key generation from attestation issuance, mandatory inclusion of server-provided cryptographically random nonces inside attestation extensions, and zero reliance on client-side certificate chain verification. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Client-Side Self-Attestation Validation and Replayable Local Nonce Generation Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftClient-Side Self-Attestation Validation and Replayable Local Nonce GenerationCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS require a server-generated, cryptographically random, ephemeral nonce (minimum 32 bytes) prior to calling hardware attestation APIs.

Engineers MUST ALWAYS require a server-generated, cryptographically random, ephemeral nonce (minimum 32 bytes) prior to calling hardware attestation APIs.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT verify X.509 certificate chains, Google Hardware Attestation Root certificates, or Apple App Attest roots locally within the mobile client application.

Engineers MUST NOT verify X.509 certificate chains, Google Hardware Attestation Root certificates, or Apple App Attest roots locally within the mobile client application.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST configure Android KeyGenParameterSpec with `setIsStrongBoxBacked(true)` and fail explicitly when StrongBoxUnavailableException is caught if strict hardware boundary is required.

Engineers MUST configure Android KeyGenParameterSpec with `setIsStrongBoxBacked(true)` and fail explicitly when StrongBoxUnavailableException is caught if strict hardware boundary is required.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Engineers MUST bind Apple DCAppAttestService attestation challenges to a SHA-256 hash of the client data containing the server nonce and public key representation.

Engineers MUST bind Apple DCAppAttestService attestation challenges to a SHA-256 hash of the client data containing the server nonce and public key representation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Code SHOULD represent platform attestation payloads uniformly in commonMain as tagged sealed classes separating Android KeyStore X.509 leaf/intermediate chains from Apple CBOR attestation statements.

Code SHOULD represent platform attestation payloads uniformly in commonMain as tagged sealed classes separating Android KeyStore X.509 leaf/intermediate chains from Apple CBOR attestation statements.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Services MUST enforce server-side replay defense by tracking consumed nonces with tight time-to-live (TTL) expiration windows (<= 60 seconds).

Services MUST enforce server-side replay defense by tracking consumed nonces with tight time-to-live (TTL) expiration windows (<= 60 seconds).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
7

Components NEVER store or attempt to serialize private key material in common code or platform memory

Components NEVER store or attempt to serialize private key material in common code or platform memory; operations must strictly execute inside isolated hardware boundaries.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is KMP Secure Hardware Key Remote Attestation Invariant Standard critical for AI coding assistants?

Enforces strict cryptographic guarantees for Kotlin Multiplatform (KMP) remote attestation unifying Android KeyStore StrongBox and Apple Secure Enclave (DCAppAttestService). Requires strict separation of client-side key generation from attestation issuance, mandatory inclusion of server-provided cryptographically random nonces inside attestation extensions, and zero reliance on client-side certificate chain verification. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Client-Side Self-Attestation Validation and Replayable Local Nonce Generation) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

KMP