examples/sign_and_verify.py
| 1 | """Sign and verify a synthetic eBPF program round-trip. |
| 2 | |
| 3 | Run: |
| 4 | python examples/sign_and_verify.py |
| 5 | """ |
| 6 | |
| 7 | from __future__ import annotations |
| 8 | |
| 9 | import json |
| 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 | SignedBPFProgram, |
| 20 | ) |
| 21 | |
| 22 | |
| 23 | def main() -> None: |
| 24 | # 1. Define the program metadata + some synthetic "bytecode". |
| 25 | metadata = BPFProgramMetadata( |
| 26 | name="trace_sys_enter_bpf", |
| 27 | program_type=BPFProgramType.KPROBE, |
| 28 | license="GPL", |
| 29 | author="ops-team", |
| 30 | description="Traces sys_enter_bpf to detect unauthorized loads.", |
| 31 | version="1.0.0", |
| 32 | kernel_min="5.15", |
| 33 | attach_point="sys_enter_bpf", |
| 34 | ) |
| 35 | bytecode = b"\x7fELF" + b"\x00" * 8 + bytes(range(256)) * 2 |
| 36 | |
| 37 | program = BPFProgram.from_bytes(metadata, bytecode) |
| 38 | print(f"Program: {metadata.name}") |
| 39 | print(f"Bytecode hash: {program.bytecode_hash}") |
| 40 | print(f"Bytecode size: {program.bytecode_size} bytes") |
| 41 | |
| 42 | # 2. Sign with an ML-DSA identity. |
| 43 | identity = AgentIdentity.create("bpf-signer", capabilities=["sign"]) |
| 44 | signer = BPFSigner(identity) |
| 45 | signed = signer.sign(program) |
| 46 | print(f"Signer DID: {signed.signer_did}") |
| 47 | print(f"Algorithm: {signed.algorithm}") |
| 48 | |
| 49 | # 3. Serialize to JSON, then restore. |
| 50 | payload = json.dumps(signed.to_dict(), indent=2) |
| 51 | restored = SignedBPFProgram.from_dict(json.loads(payload)) |
| 52 | |
| 53 | # 4. Verify the restored envelope. |
| 54 | result = BPFVerifier.verify(restored) |
| 55 | print(f"Verify valid: {result.valid}") |
| 56 | print(f"Signature OK: {result.signature_valid}") |
| 57 | print(f"Hash OK: {result.hash_consistent}") |
| 58 | assert result.valid |
| 59 | |
| 60 | |
| 61 | if __name__ == "__main__": |
| 62 | main() |
| 63 | |