omnet
aien-dev/omnet
Brought by drakestapleton
omnet / cmd / tkad / test / mutant.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 |
| 3 | import pathlib |
| 4 | import subprocess |
| 5 | import sys |
| 6 | |
| 7 | root, binary = map(pathlib.Path, sys.argv[1:]) |
| 8 | source = pathlib.Path(str(binary) + ".om").read_text() |
| 9 | omc = subprocess.check_output(["sh", str(root / "tools/omc.sh")], text=True).strip() |
| 10 | needle = "fn dsbegin t view ulong 32768 d view uchar 65536 out edit uchar 65536 to int\nif eq get ds_ctl 3 0\nret 403\nend" |
| 11 | assert source.count(needle) == 1 |
| 12 | variants = { |
| 13 | "admin-bypass": needle.replace("if eq get ds_ctl 3 0", "if eq get ds_ctl 3 2"), |
| 14 | "trap": needle.replace("ret 403", "trap 1"), |
| 15 | } |
| 16 | for label, replacement in variants.items(): |
| 17 | path = root / "build" / ("tkad-mutant-" + label) |
| 18 | build = subprocess.run([omc], input=source.replace(needle, replacement).encode(), capture_output=True) |
| 19 | assert build.returncode == 0, build.stderr.decode() |
| 20 | path.write_bytes(build.stdout) |
| 21 | path.chmod(0o700) |
| 22 | run = subprocess.run([sys.executable, str(root / "cmd/tkad/test/smoke.py"), str(path), "--probe"], capture_output=True, text=True, timeout=60) |
| 23 | completed_mismatch = run.returncode != 0 and "expected 403, got 200" in run.stderr |
| 24 | if label == "admin-bypass": |
| 25 | assert completed_mismatch, (run.returncode, run.stdout, run.stderr) |
| 26 | print("PASS tkad completed-response admin-bypass mutant detected") |
| 27 | else: |
| 28 | assert run.returncode != 0 and not completed_mismatch and "truncated daemon reply" in run.stderr, (run.returncode, run.stdout, run.stderr) |
| 29 | print("PASS tkad trapping mutant rejected, not counted as detection") |
| 30 | |
| 31 | note_guard = "if and eq dsget 9 0 eq dsget 10 0\nret 1\nend\n" |
| 32 | assert source.count(note_guard) == 1 |
| 33 | path = root / "build" / "tkad-mutant-no-identity" |
| 34 | build = subprocess.run([omc], input=source.replace(note_guard, "").encode(), capture_output=True) |
| 35 | assert build.returncode == 0, build.stderr.decode() |
| 36 | path.write_bytes(build.stdout) |
| 37 | path.chmod(0o700) |
| 38 | probe = subprocess.run([sys.executable, str(root / "cmd/tkad/test/identity.py"), str(path), "--probe"], capture_output=True, text=True, timeout=120) |
| 39 | assert probe.returncode == 0, ("mutant without the identity guard was not caught", probe.returncode, probe.stdout, probe.stderr) |
| 40 | probe = subprocess.run([sys.executable, str(root / "cmd/tkad/test/identity.py"), str(binary), "--probe"], capture_output=True, text=True, timeout=120) |
| 41 | assert probe.returncode == 3, ("production binary must refuse a zero identity", probe.returncode, probe.stdout, probe.stderr) |
| 42 | print("PASS tkad identity guard mutant detected, and the production guard refuses") |