examples/detect_memory_tampering.py
1.9 KB · 70 lines · python Raw
1 """Detect in-VM memory tampering.
2
3 Attest clean state, mutate a region (simulating an attacker rewriting model
4 weights), attest again — the verifier must flag drift on the second report.
5 """
6
7 from __future__ import annotations
8
9 from quantumshield.identity.agent import AgentIdentity
10
11 from pqc_hypervisor_attestation import (
12 AttestationVerifier,
13 Attester,
14 ContinuousAttester,
15 InMemoryBackend,
16 MemoryRegion,
17 RegionSnapshot,
18 )
19
20 WORKLOAD_ID = "model-serving-1"
21
22
23 def main() -> None:
24 identity = AgentIdentity.create(
25 name="tamper-detector",
26 capabilities=["attest"],
27 )
28 attester = Attester(identity)
29
30 backend = InMemoryBackend()
31 weights = MemoryRegion(
32 region_id="model-weights-0",
33 description="Llama weight shard 0",
34 address=0x1000,
35 size=32,
36 protection="RO",
37 )
38 trusted = b"MODEL-WEIGHTS-TRUSTED-PAYLOAD-01"
39 backend.register(WORKLOAD_ID, weights, trusted)
40
41 loop = ContinuousAttester(
42 attester=attester,
43 backend=backend,
44 workload_id=WORKLOAD_ID,
45 expected_hashes={weights.region_id: RegionSnapshot.hash_bytes(trusted)},
46 )
47
48 # 1. Clean attestation.
49 clean = loop.attest_once()
50 clean_result = AttestationVerifier.verify(clean, strict=True)
51 print("[clean]")
52 print(f" valid : {clean_result.valid}")
53 print(f" drifts : {clean_result.drifts}")
54
55 # 2. Simulated attacker tampering.
56 backend.update(weights.region_id, b"MODEL-WEIGHTS-COMPROMISED!!!!!!!")
57
58 # 3. Tampered attestation.
59 dirty = loop.attest_once()
60 dirty_result = AttestationVerifier.verify(dirty, strict=True)
61 print("[tampered]")
62 print(f" valid : {dirty_result.valid}")
63 print(f" signature_valid : {dirty_result.signature_valid}")
64 print(f" drifts : {dirty_result.drifts}")
65 print(f" error : {dirty_result.error}")
66
67
68 if __name__ == "__main__":
69 main()
70