Add Keystone with a reproducible x86-64/ARM64 assembly round-trip check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019S6gW1R7hWkvBKbBYnSYgK
This commit is contained in:
aftabkh4n
2026-10-25 05:24:17 +00:00
parent 0d7e3bb4ed
commit 857d863aed
6 changed files with 99 additions and 13 deletions
+1
View File
@@ -239,6 +239,7 @@ Run samples only in isolated, disposable environments, and follow your organizat
- [Capstone](https://github.com/capstone-engine/capstone) - Multi-architecture disassembly library for building analysis tools.
- [Diaphora](https://github.com/joxeankoret/diaphora) - Binary diffing plugin for comparing functions and transferring analysis in IDA.
- [ghidriff](https://github.com/clearbluejar/ghidriff) - Ghidra-based command-line binary diffing engine with JSON, Markdown, and optional HTML reports; requires compatible Ghidra, PyGhidra, and JDK versions.
- [Keystone](https://github.com/keystone-engine/keystone) - Multi-architecture assembler library, the counterpart to Capstone, for turning assembly text into machine code when patching binaries or building test inputs; GPL-2.0 with a separate commercial license, and the latest PyPI release (0.9.2, 2020) ships wheels only for x86 and x86-64 hosts.
- [Miasm](https://github.com/cea-sec/miasm) - Python reverse-engineering framework with an intermediate representation, emulation, symbolic execution, and assemblers and disassemblers for several architectures.
- [Qiling](https://github.com/qilingframework/qiling) - Emulates binaries with operating-system services for scripted runtime analysis.
- [Triton](https://github.com/JonathanSalwan/Triton) - Dynamic binary analysis library with symbolic execution, taint analysis, and AST representations of instruction semantics, usable from C++ or Python.
+9 -1
View File
@@ -1,6 +1,6 @@
# Bounded resource examples
These self-authored fixtures demonstrate Construct, Scapy, YARA-X, Vineflower, Malduck, hermes-dec, MemProcFS, and boofuzz in CI, plus a local PyLingual check. They are small selection examples, not upstream test suites or evidence of full platform/version support.
These self-authored fixtures demonstrate Construct, Scapy, YARA-X, Vineflower, Malduck, hermes-dec, MemProcFS, boofuzz, and Keystone in CI, plus a local PyLingual check. They are small selection examples, not upstream test suites or evidence of full platform/version support.
Use Python 3.11 with `venv`/`pip` support, JDK 17, Node.js, and an Internet connection for the pinned packages, JAR, and Hermes compilers. From the repository root:
@@ -17,6 +17,8 @@ The Hermes fixture additionally needs Node.js (CI uses Node.js 22). Its pinned c
MemProcFS runs only on Linux x86-64, where it also needs the system `libusb-1.0` library (`sudo apt-get install libusb-1.0-0` on Debian/Ubuntu). Its pinned wheels are installed only on that host, and on other hosts the runner records MemProcFS as `skipped`.
Keystone and Capstone are also installed and exercised only on Linux x86-64. Keystone 0.9.2 has no wheel for ARM hosts, where pip would build it from source with CMake and a C++ compiler; on other hosts the runner records Keystone as `skipped`.
On Windows, use this PowerShell block with Python 3.11 and JDK 17 or newer (`java` and `javac` on `PATH`). The verifier checks both Java versions before running the fixtures. Use `python` in place of `py -3.11` if that is your Python 3.11 launcher.
```powershell
@@ -38,6 +40,7 @@ $resourcePython = Join-Path $resourceExamplesDir "venv\Scripts\python.exe"
| hermes-dec 0.1.8 | [`hbc_fixture.js`](hbc_fixture.js) compiled by `hermes-compiler` 250829098.0.19 (HBC 98) and 260318099.0.4 (HBC 99) at `-g0` and `-g1`; header version, disassembly, and pseudo-code landmarks (function names, strings, `<Mod>`, constant `7`) | See the limits below |
| MemProcFS 5.19.0 | A 16 MiB raw image with a self-built x64 page table; with `-dtb 0x10000` the [probe](memprocfs_probe.py) shows one `unknown_process`, reads `MPFS-PHYS-MARK-1` at physical `0x1000` and through `/memory.pmem`, and translates `0x140001678` to physical `0x345678` where it reads `MPFS-VIRT-MARK-2` | Physical-memory, page-table, and virtual-file-system API on Linux x86-64 only; no Windows OS analysis |
| boofuzz 0.4.2 | A made-up TRC1 protocol (`TRC1`, kind, big-endian length, payload, big-endian CRC-32) described with `Size` and `Checksum` blocks; the default frame matches bytes built with `struct` and `zlib`, and a localhost server receives all 575 payload mutations with a correct length and CRC, replying to each | One-field-at-a-time fuzzing (`max_depth=1`) against a localhost server only; see the limits below |
| Keystone 0.9.2 (with Capstone 5.0.9) | x86-64 `push rbp; mov rbp, rsp; mov eax, dword ptr [rbx + rcx*4 + 8]; xor eax, eax; pop rbp; ret` and ARM64 `mov x0, #1; add x1, x2, x3; ldr x0, [x1, #8]; b #0x1010; ret` at base `0x1000` assemble to bytes encoded by hand from the Intel SDM and Arm ARM (`554889e58b448b0831c05dc3`, `200080d24100038b200440f901000014c0035fd6`); Capstone disassembles them back to the same text, which reassembles to the same bytes; `b #0x1010` at `0x2000` becomes the backward branch `04fcff17` | Two short sequences on two ISAs, Linux x86-64 only; see the limits below |
The branch oracle for `Probe.java` is:
@@ -61,6 +64,11 @@ The boofuzz check also records three limits:
- `String` mutations are text: byte patterns such as `\xde\xad\xbe\xef` are sent UTF-8 encoded, and `max_len` counts characters, so a 48-character limit produced a 96-byte payload.
- Without a process monitor or restart callback, a target that stops listening ends the run after 17 of 575 cases with only an info message ("Ending fuzzing"); no test case is marked failed and `fuzz()` returns normally.
The Keystone check also records two limits:
- Relative branches and RIP-relative operands are encoded against the address passed to `asm()`, so the same text gives different bytes at another base.
- An unknown mnemonic fails with `KS_ERR_ASM_MNEMONICFAIL`, but an ARM64 immediate that one `MOV` cannot encode (`mov x0, #0x12345678`) fails with errno 561, which the 0.9.2 Python binding has no constant for and reports only as "Unknown error".
Without `-dtb`, MemProcFS rejects a raw image that contains no identifiable operating system (`Unable to locate valid DTB`). The Linux `memprocfs` wheel does not include `leechcore.so`; the runner uses the one from `leechcorepyc` by starting the probe with `LD_LIBRARY_PATH` pointing at its directory.
The [dated local result](verified.json) records host/tool versions, input hashes, artifact digests, and the tested scope; it was produced in a Linux x86_64 container. CI repeats the examples and uploads current results through the [resource-example workflow](../../.github/workflows/resource-examples.yml). The current job uses Linux x86-64, Python 3.11, Java 17, Node.js 22, and `libusb-1.0`; it makes no Windows, macOS, hardware, or other-version claim.
@@ -6,3 +6,5 @@ malduck==4.4.1
boofuzz==0.4.2
memprocfs==5.19.0; sys_platform == "linux" and platform_machine == "x86_64"
leechcorepyc==2.23.3; sys_platform == "linux" and platform_machine == "x86_64"
keystone-engine==0.9.2; sys_platform == "linux" and platform_machine == "x86_64"
capstone==5.0.9; sys_platform == "linux" and platform_machine == "x86_64"
+27 -9
View File
@@ -1,10 +1,10 @@
{
"checked_at": "2026-10-24T14:08:49.502647+00:00",
"checked_at": "2026-10-25T05:23:00.315217+00:00",
"host": {
"platform": "Linux-6.1.0-54-cloud-amd64-x86_64-with-glibc2.36",
"python": "3.11.2",
"javac": "javac 17.0.20.1",
"node": "v20.20.2"
"platform": "Linux-6.18.44-fc-v153-x86_64-with-glibc2.39",
"python": "3.11.17",
"javac": "javac 21.0.12.1",
"node": "v22.22.0"
},
"results": [
{
@@ -54,6 +54,12 @@
"version": "5.19.0",
"result": "passed",
"scope": "Self-authored raw image: physical read, user-supplied DTB fallback process, virtual read, virt2phys, /memory.pmem; no Windows OS analysis"
},
{
"name": "Keystone",
"version": "0.9.2",
"result": "passed",
"scope": "x86-64 and ARM64: hand-encoded bytes, Capstone 5.0.9 disassembly and reassembly, base-relative branch, mnemonic error code; an unencodable ARM64 immediate reports errno 561 as \"Unknown error\""
}
],
"inputs": [
@@ -83,11 +89,11 @@
},
{
"path": "verify.py",
"sha256": "e2ac23876d6c535f5355a836c3269caaaeb7e10f94b105e976116180a6b18e38"
"sha256": "617c1e694c5b7effdc30dde5cb3164641fd8742577600d06ebd2c3657a53f696"
},
{
"path": "requirements.txt",
"sha256": "ca1e1d2f17a1c624b3f3ff46678acfcbac9fdee4fc23c5510cfb5653abf6cc79"
"sha256": "7cb39a2d7055d308366664a6aea5087ca494f0b201d03c020da7bf25c50a9ef9"
}
],
"golden_hex": "534d4b310500017472616365",
@@ -129,11 +135,11 @@
"hbc_sha256": {
"98": {
"g0": "d1ceacc1f40097b798abf4eeaf8f2f0a663afa9ed8d8fdd5f2b2d99ee2e422a8",
"g1": "ffd55f5d6d81b2a82a2700138028f58d019d8f317654c31266ff3800e06ae25e"
"g1": "9ea2749d21a627d5a6ff5fc61a4ddd79486e79040525cc2537cc7af5663b4f0d"
},
"99": {
"g0": "f51e55203c85ab6fd016ab83862f81aa61cc2f441087c10ef712c2148bf7b57d",
"g1": "9b6527d960d7363abb2f7a0be3cfa18240156aad9adfcd61107e98e4efd7caaf"
"g1": "5bec92f01a71016d39313955ce2dd363d0e59b969b1abe70f0a803c69ff507af"
}
},
"original_output": "even:negative:25",
@@ -149,5 +155,17 @@
"dtb": "0x10000",
"virtual_address": "0x140001678",
"physical_address": "0x345678"
},
"keystone": {
"base": "0x1000",
"x64": {
"source": "push rbp; mov rbp, rsp; mov eax, dword ptr [rbx + rcx*4 + 8]; xor eax, eax; pop rbp; ret",
"bytes": "554889e58b448b0831c05dc3"
},
"arm64": {
"source": "mov x0, #1; add x1, x2, x3; ldr x0, [x1, #8]; b #0x1010; ret",
"bytes": "200080d24100038b200440f901000014c0035fd6",
"backward_branch_at_0x2000": "04fcff17"
}
}
}
+58 -1
View File
@@ -1,4 +1,4 @@
"""Reproduce eight narrow resource examples with independent expected outputs."""
"""Reproduce nine narrow resource examples with independent expected outputs."""
import argparse
import ctypes.util
from datetime import datetime, timezone
@@ -44,6 +44,15 @@ TRC1_CASES = 575
MEMPROCFS_PACKAGES = {"memprocfs": "5.19.0", "leechcorepyc": "2.23.3"}
PML4, PDPT, PD, PT, PAGE = 0x10000, 0x11000, 0x12000, 0x13000, 0x345000
FIXTURE_VA = 0x140001678
KEYSTONE_PACKAGES = {"keystone-engine": "0.9.2", "capstone": "5.0.9"}
ASM_BASE = 0x1000
# Expected bytes are encoded by hand from the Intel SDM and Arm ARM opcode tables, not by either library.
X64_SOURCE = "push rbp; mov rbp, rsp; mov eax, dword ptr [rbx + rcx*4 + 8]; xor eax, eax; pop rbp; ret"
X64_BYTES = "554889e58b448b0831c05dc3"
A64_SOURCE = "mov x0, #1; add x1, x2, x3; ldr x0, [x1, #8]; b #0x1010; ret"
A64_BYTES = "200080d24100038b200440f901000014c0035fd6"
# The same `b #0x1010` assembled at 0x2000 is a backward branch: imm26 = (0x1010 - 0x2000) / 4.
A64_BACKWARD_BRANCH = "04fcff17"
def sha256(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
@@ -284,10 +293,17 @@ def memprocfs_host():
return platform.system() == "Linux" and platform.machine() == "x86_64"
def keystone_host():
# Keystone 0.9.2 has no ARM-host wheels (pip would build it from source); only Linux x86-64 is exercised here.
return platform.system() == "Linux" and platform.machine() == "x86_64"
def required_packages():
packages = {"construct": "2.10.70", "scapy": "2.8.0", "yara-x": "1.21.0", "hermes-dec": "0.1.8", "malduck": "4.4.1", "boofuzz": "0.4.2"}
if memprocfs_host():
packages.update(MEMPROCFS_PACKAGES)
if keystone_host():
packages.update(KEYSTONE_PACKAGES)
return packages
@@ -325,6 +341,40 @@ def verify_memprocfs(work):
return sha256(image)
def verify_keystone():
import capstone
import keystone
cases = [
(keystone.KS_ARCH_X86, keystone.KS_MODE_64, capstone.CS_ARCH_X86, capstone.CS_MODE_64, X64_SOURCE, X64_BYTES),
(keystone.KS_ARCH_ARM64, keystone.KS_MODE_LITTLE_ENDIAN, capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM, A64_SOURCE, A64_BYTES),
]
for ks_arch, ks_mode, cs_arch, cs_mode, source, expected in cases:
assembler = keystone.Ks(ks_arch, ks_mode)
encoding, count = assembler.asm(source, ASM_BASE)
assert bytes(encoding).hex() == expected and count == source.count(";") + 1, (source, bytes(encoding).hex(), count)
text = "; ".join(f"{insn.mnemonic} {insn.op_str}".strip() for insn in capstone.Cs(cs_arch, cs_mode).disasm(bytes.fromhex(expected), ASM_BASE))
assert text == source, text
assert bytes(assembler.asm(text, ASM_BASE)[0]).hex() == expected
arm64 = keystone.Ks(keystone.KS_ARCH_ARM64, keystone.KS_MODE_LITTLE_ENDIAN)
# Relative branches are encoded against the address passed to asm().
assert bytes(arm64.asm("b #0x1010", 0x2000)[0]).hex() == A64_BACKWARD_BRANCH
try:
keystone.Ks(keystone.KS_ARCH_X86, keystone.KS_MODE_64).asm("foo eax")
except keystone.KsError as exc:
assert exc.errno == keystone.KS_ERR_ASM_MNEMONICFAIL, exc.errno
else:
raise AssertionError("Unknown mnemonic unexpectedly assembled")
# An immediate that one MOV cannot encode fails with errno 561, which the 0.9.2 binding reports as "Unknown error".
try:
arm64.asm("mov x0, #0x12345678")
except keystone.KsError as exc:
assert exc.errno == 561 and str(exc) == "Unknown error", (exc.errno, str(exc))
else:
raise AssertionError("Unencodable immediate unexpectedly assembled")
def verify(work, jar):
for package, expected in required_packages().items():
try:
@@ -409,6 +459,10 @@ def verify(work, jar):
duck_digest = verify_malduck(work)
hbc_digests = verify_hermes_dec(work)
boofuzz_summary = verify_boofuzz(work)
keystone_result = {"name": "Keystone", "version": "0.9.2", "result": "skipped", "scope": "This check runs on Linux x86-64 only"}
if keystone_host():
verify_keystone()
keystone_result.update(result="passed", scope="x86-64 and ARM64: hand-encoded bytes, Capstone 5.0.9 disassembly and reassembly, base-relative branch, mnemonic error code; an unencodable ARM64 immediate reports errno 561 as \"Unknown error\"")
memprocfs = {"name": "MemProcFS", "version": "5.19.0", "result": "skipped", "scope": "This check runs on Linux x86-64 only"}
image_digest = None
if memprocfs_host():
@@ -427,6 +481,7 @@ def verify(work, jar):
{"name": "hermes-dec", "version": "0.1.8", "result": "passed", "scope": "HBC 98/99 at -g0/-g1: header, disassembly and pseudo-code landmarks; -g1 debug-info parsing raises TypeError; executing the pseudo-code prints 21, not 25"},
{"name": "boofuzz", "version": "0.4.2", "result": "passed", "scope": "Localhost TRC1 protocol: default frame, 575 payload mutations with correct length/CRC, sent and replied frames match; replies unread by default, UTF-8 string mutations, and a stopped target ends the run without a failure"},
memprocfs,
keystone_result,
],
"inputs": [{"path": name, "sha256": sha256(SOURCE / name)} for name in ("BranchDemo.java", "Probe.java", "hbc_fixture.js", "malduck_modules/duckcfg/__init__.py", "malduck_modules/duckcfg/duckcfg.yar", "memprocfs_probe.py", "verify.py", "requirements.txt")],
"golden_hex": GOLDEN.hex(),
@@ -438,6 +493,8 @@ def verify(work, jar):
"original_output": HBC_ORIGINAL_OUTPUT, "pseudocode_output": HBC_PSEUDOCODE_OUTPUT},
"boofuzz": boofuzz_summary,
"memprocfs": {"image_sha256": image_digest, "dtb": hex(PML4), "virtual_address": hex(FIXTURE_VA), "physical_address": hex(PAGE + 0x678)},
"keystone": {"base": hex(ASM_BASE), "x64": {"source": X64_SOURCE, "bytes": X64_BYTES},
"arm64": {"source": A64_SOURCE, "bytes": A64_BYTES, "backward_branch_at_0x2000": A64_BACKWARD_BRANCH}},
}
+2 -2
View File
@@ -21,9 +21,9 @@ spec.loader.exec_module(verifier)
# Independent of the verifier: (sys_platform, platform_machine) -> packages pip should install beyond the
# always-required pins. MemProcFS is exercised only on Linux x86-64.
# always-required pins. MemProcFS and Keystone are exercised only on Linux x86-64.
HOST_MATRIX = {
("linux", "x86_64"): {"memprocfs", "leechcorepyc"},
("linux", "x86_64"): {"memprocfs", "leechcorepyc", "keystone-engine", "capstone"},
("linux", "aarch64"): set(),
("darwin", "arm64"): set(),
("darwin", "x86_64"): set(),