examples/tampered_bytecode_rejected.py
| 1 | """Show that mutating the bytecode of a SignedBPFProgram fails verification. |
| 2 | |
| 3 | Run: |
| 4 | python examples/tampered_bytecode_rejected.py |
| 5 | """ |
| 6 | |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | from dataclasses import replace |
| 10 | |
| 11 | from quantumshield.identity.agent import AgentIdentity |
| 12 | |
| 13 | from pqc_ebpf_attestation import ( |
| 14 | BPFProgram, |
| 15 | BPFProgramMetadata, |
| 16 | BPFProgramType, |
| 17 | BPFSigner, |
| 18 | BPFVerifier, |
| 19 | ) |
| 20 | |
| 21 | |
| 22 | def main() -> None: |
| 23 | metadata = BPFProgramMetadata( |
| 24 | name="xdp_filter_ddos", |
| 25 | program_type=BPFProgramType.XDP, |
| 26 | license="GPL", |
| 27 | attach_point="eth0", |
| 28 | ) |
| 29 | original_bytecode = b"\x7fELFGOOD" + b"\x00" * 256 |
| 30 | program = BPFProgram.from_bytes(metadata, original_bytecode) |
| 31 | |
| 32 | identity = AgentIdentity.create("bpf-signer") |
| 33 | signed = BPFSigner(identity).sign(program) |
| 34 | |
| 35 | # Verify the untampered envelope first. |
| 36 | clean = BPFVerifier.verify(signed) |
| 37 | print(f"Clean envelope valid: {clean.valid}") |
| 38 | print(f" signature_valid: {clean.signature_valid}") |
| 39 | print(f" hash_consistent: {clean.hash_consistent}") |
| 40 | print() |
| 41 | |
| 42 | # Mutate the bytecode bytes AFTER signing. The stored hash no longer matches. |
| 43 | tampered_program = replace( |
| 44 | signed.program, bytecode=signed.program.bytecode[:-4] + b"EVIL" |
| 45 | ) |
| 46 | tampered = replace(signed, program=tampered_program) |
| 47 | |
| 48 | result = BPFVerifier.verify(tampered) |
| 49 | print(f"Tampered envelope valid: {result.valid}") |
| 50 | print(f" signature_valid: {result.signature_valid}") |
| 51 | print(f" hash_consistent: {result.hash_consistent}") |
| 52 | print(f" error: {result.error}") |
| 53 | |
| 54 | |
| 55 | if __name__ == "__main__": |
| 56 | main() |
| 57 | |