Skip to content

armgit / kong

Public Imported from GitHub
0

The world's first agentic reverse engineer.

add/update tests for analyzer/triage agents and supervisor agent

Amruthe29da0d03d56
diff --git a/tests/test_agent_analyzer.py b/tests/test_agent_analyzer.py
new file mode 100644
index 0000000..1b3e584
--- /dev/null
+++ b/tests/test_agent_analyzer.py
@@ -0,0 +1,272 @@
+"""Tests for the analyzer agent."""
+
+from unittest.mock import MagicMock, patch
+
+from kong.agent.analyzer import (
+ Analyzer,
+ AnalysisContext,
+ CallerSnippet,
+ CalleeSnippet,
+ LLMResponse,
+ VariableRename,
+)
+from kong.agent.queue import WorkItem
+from kong.agent.models import FunctionResult
+from kong.ghidra.types import (
+ BinaryInfo,
+ FunctionClassification,
+ FunctionInfo,
+ StringEntry,
+ XRef,
+)
+
+
+def _func(addr=0x1000, name="FUN_00001000", size=100):
+ return FunctionInfo(
+ address=addr, name=name, size=size,
+ classification=FunctionClassification.MEDIUM,
+ )
+
+
+def _item(addr=0x1000, name="FUN_00001000", callers=None, callees=None):
+ return WorkItem(
+ function=_func(addr, name),
+ callers=callers or [],
+ callees=callees or [],
+ )
+
+
+def _binary_info():
+ return BinaryInfo(
+ arch="x86-64", format="ELF", endianness="little",
+ word_size=8, compiler="GCC",
+ )
+
+
+def _mock_llm(response: LLMResponse):
+ llm = MagicMock()
+ llm.analyze_function.return_value = response
+ return llm
+
+
+def _mock_client():
+ client = MagicMock()
+ client.get_decompilation.return_value = "void FUN_00001000(void) { return; }"
+ client.get_function_info.return_value = _func()
+ client.get_xrefs_from.return_value = []
+ return client
+
+
+class TestAnalyzerAnalyze:
+ def test_basic_analysis(self):
+ response = LLMResponse(
+ name="init_module",
+ signature="void init_module(void)",
+ confidence=85,
+ classification="init",
+ comments="Initializes the module",
+ reasoning="Single initialization call pattern",
+ )
+ llm = _mock_llm(response)
+ client = _mock_client()
+
+ analyzer = Analyzer(client, llm)
+ result = analyzer.analyze(_item(), _binary_info(), {}, [])
+
+ assert result.name == "init_module"
+ assert result.signature == "void init_module(void)"
+ assert result.confidence == 85
+ assert result.classification == "init"
+ assert result.llm_calls == 1
+
+ def test_writes_back_to_ghidra(self):
+ response = LLMResponse(
+ name="decrypt_data",
+ signature="void decrypt_data(char *buf, int len)",
+ comments="Decrypts buffer using XOR",
+ )
+ llm = _mock_llm(response)
+ client = _mock_client()
+
+ analyzer = Analyzer(client, llm)
+ analyzer.analyze(_item(), _binary_info(), {}, [])
+
+ client.rename_function.assert_called_once_with(0x1000, "decrypt_data")
+ client.set_function_signature.assert_called_once_with(
+ 0x1000, "void decrypt_data(char *buf, int len)"
+ )
+ client.add_comment.assert_called_once_with(0x1000, "Decrypts buffer using XOR")
+
+ def test_skips_empty_writeback_fields(self):
+ response = LLMResponse(name="foo")
+ llm = _mock_llm(response)
+ client = _mock_client()
+
+ analyzer = Analyzer(client, llm)
+ analyzer.analyze(_item(), _binary_info(), {}, [])
+
+ client.rename_function.assert_called_once()
+ client.set_function_signature.assert_not_called()
+ client.add_comment.assert_not_called()
+
+ def test_writeback_failure_doesnt_crash(self):
+ response = LLMResponse(name="bad_name!@#")
+ llm = _mock_llm(response)
+ client = _mock_client()
+ client.rename_function.side_effect = Exception("Invalid name")
+
+ analyzer = Analyzer(client, llm)
+ result = analyzer.analyze(_item(), _binary_info(), {}, [])
+
+ assert result.name == "bad_name!@#"
+
+
+class TestAnalyzerContext:
+ def test_includes_decompilation(self):
+ llm = _mock_llm(LLMResponse(name="f"))
+ client = _mock_client()
+ client.get_decompilation.return_value = "int main() { return 0; }"
+
+ analyzer = Analyzer(client, llm)
+ analyzer.analyze(_item(), _binary_info(), {}, [])
+
+ prompt = llm.analyze_function.call_args[0][0]
+ assert "int main() { return 0; }" in prompt
+
+ def test_includes_binary_info(self):
+ llm = _mock_llm(LLMResponse(name="f"))
+ client = _mock_client()
+
+ analyzer = Analyzer(client, llm)
+ analyzer.analyze(_item(), _binary_info(), {}, [])
+
+ prompt = llm.analyze_function.call_args[0][0]
+ assert "x86-64" in prompt
+ assert "ELF" in prompt
+
+ def test_includes_callee_snippets(self):
+ llm = _mock_llm(LLMResponse(name="f"))
+ client = _mock_client()
+ client.get_decompilation.side_effect = lambda addr: (
+ "void callee() { stuff; }" if addr == 0x2000
+ else "void target() { callee(); }"
+ )
+
+ item = _item(callees=[0x2000])
+ analyzer = Analyzer(client, llm)
+ analyzer.analyze(item, _binary_info(), {}, [])
+
+ prompt = llm.analyze_function.call_args[0][0]
+ assert "Called Functions" in prompt
+ assert "callee" in prompt
+
+ def test_includes_caller_snippets(self):
+ llm = _mock_llm(LLMResponse(name="f"))
+ client = _mock_client()
+ client.get_decompilation.side_effect = lambda addr: (
+ "void caller() { target(); }" if addr == 0x3000
+ else "void target() { return; }"
+ )
+
+ item = _item(callers=[0x3000])
+ analyzer = Analyzer(client, llm)
+ analyzer.analyze(item, _binary_info(), {}, [])
+
+ prompt = llm.analyze_function.call_args[0][0]
+ assert "Calling Functions" in prompt
+
+ def test_includes_referenced_strings(self):
+ llm = _mock_llm(LLMResponse(name="f"))
+ client = _mock_client()
+ client.get_xrefs_from.return_value = [
+ XRef(from_addr=0x1000, to_addr=0x5000, ref_type="DATA"),
+ ]
+ strings = [StringEntry(address=0x5000, value="Hello, World!")]
+
+ analyzer = Analyzer(client, llm)
+ analyzer.analyze(_item(), _binary_info(), {}, strings)
+
+ prompt = llm.analyze_function.call_args[0][0]
+ assert "Hello, World!" in prompt
+
+ def test_includes_known_functions(self):
+ llm = _mock_llm(LLMResponse(name="f"))
+ client = _mock_client()
+
+ known = {
+ 0x2000: FunctionResult(
+ address=0x2000, original_name="FUN_2000",
+ name="rc4_init", confidence=90,
+ ),
+ }
+
+ analyzer = Analyzer(client, llm)
+ analyzer.analyze(_item(), _binary_info(), known, [])
+
+ prompt = llm.analyze_function.call_args[0][0]
+ assert "rc4_init" in prompt
+ assert "Already Identified" in prompt
+
+ def test_uses_known_name_for_callee(self):
+ """When a callee has already been analyzed, use its resolved name."""
+ llm = _mock_llm(LLMResponse(name="f"))
+ client = _mock_client()
+ client.get_decompilation.return_value = "void f() {}"
+
+ known = {
+ 0x2000: FunctionResult(
+ address=0x2000, original_name="FUN_2000",
+ name="malloc_wrapper", confidence=80,
+ ),
+ }
+
+ item = _item(callees=[0x2000])
+ analyzer = Analyzer(client, llm)
+ ctx = analyzer._build_context(item, _binary_info(), known, [])
+
+ callee_names = [c.name for c in ctx.callee_snippets]
+ assert "malloc_wrapper" in callee_names
+
+
+class TestParseLLMJson:
+ def test_parse_clean_json(self):
+ raw = '{"name": "init", "signature": "void init()", "confidence": 90, "classification": "init", "comments": "init func", "reasoning": "obvious"}'
+ resp = Analyzer.parse_llm_json(raw)
+ assert resp.name == "init"
+ assert resp.confidence == 90
+
+ def test_parse_fenced_json(self):
+ raw = 'Here is my analysis:\n```json\n{"name": "parse_args", "confidence": 75}\n```\nDone.'
+ resp = Analyzer.parse_llm_json(raw)
+ assert resp.name == "parse_args"
+ assert resp.confidence == 75
+
+ def test_parse_bare_fenced(self):
+ raw = '```\n{"name": "foo"}\n```'
+ resp = Analyzer.parse_llm_json(raw)
+ assert resp.name == "foo"
+
+ def test_parse_with_variables(self):
+ raw = '{"name": "f", "variables": [{"old_name": "var1", "new_name": "count"}, {"old_name": "var2", "new_name": "buffer"}]}'
+ resp = Analyzer.parse_llm_json(raw)
+ assert len(resp.variables) == 2
+ assert resp.variables[0].old_name == "var1"
+ assert resp.variables[0].new_name == "count"
+
+ def test_parse_invalid_json(self):
+ raw = "This is not JSON at all"
+ resp = Analyzer.parse_llm_json(raw)
+ assert resp.name == ""
+ assert "Failed to parse" in resp.reasoning
+
+ def test_parse_missing_fields(self):
+ raw = '{"name": "f"}'
+ resp = Analyzer.parse_llm_json(raw)
+ assert resp.name == "f"
+ assert resp.confidence == 0
+ assert resp.classification == ""
+
+ def test_parse_preserves_raw(self):
+ raw = '{"name": "test"}'
+ resp = Analyzer.parse_llm_json(raw)
+ assert resp.raw == raw
diff --git a/tests/test_agent_supervisor.py b/tests/test_agent_supervisor.py
index 054c85b..1e522c5 100644
--- a/tests/test_agent_supervisor.py
+++ b/tests/test_agent_supervisor.py
@@ -3,7 +3,8 @@
from unittest.mock import MagicMock, patch
from kong.agent.events import Event, EventType, Phase
-from kong.agent.supervisor import AnalysisStats, FunctionResult, Supervisor
+from kong.agent.models import FunctionResult
+from kong.agent.supervisor import AnalysisStats, Supervisor
from kong.config import KongConfig, OutputConfig
from kong.ghidra.types import BinaryInfo, FunctionClassification, FunctionInfo
diff --git a/tests/test_agent_triage.py b/tests/test_agent_triage.py
new file mode 100644
index 0000000..f489f16
--- /dev/null
+++ b/tests/test_agent_triage.py
@@ -0,0 +1,261 @@
+"""Tests for the triage agent and signature matching."""
+
+from pathlib import Path
+from unittest.mock import MagicMock
+
+from kong.agent.signatures import SignatureDB, SignatureMatch
+from kong.agent.triage import CallGraph, LanguageHints, TriageAgent, TriageResult
+from kong.ghidra.types import BinaryInfo, FunctionClassification, FunctionInfo, StringEntry
+
+
+SIGNATURES_DIR = Path(__file__).parent.parent / "kong" / "signatures"
+
+
+def _func(addr, name, size=100, cls=FunctionClassification.MEDIUM):
+ return FunctionInfo(address=addr, name=name, size=size, classification=cls)
+
+
+def _make_client(functions=None, binary_info=None, strings=None):
+ client = MagicMock()
+ client.get_binary_info.return_value = binary_info or BinaryInfo(
+ arch="x86-64", format="ELF", endianness="little", word_size=8,
+ compiler="GCC", name="test_binary",
+ )
+ client.list_functions.return_value = functions or []
+ client.get_strings.return_value = strings or []
+ client.get_callers.return_value = []
+ client.get_callees.return_value = []
+ return client
+
+
+# ── SignatureDB ──────────────────────────────────────────────
+
+
+class TestSignatureDB:
+ def test_load_stdlib(self):
+ db = SignatureDB()
+ count = db.load_file(SIGNATURES_DIR / "stdlib.json")
+ assert count > 30
+ assert db.size > 30
+
+ def test_load_crypto(self):
+ db = SignatureDB()
+ count = db.load_file(SIGNATURES_DIR / "crypto.json")
+ assert count > 5
+
+ def test_load_directory(self):
+ db = SignatureDB()
+ total = db.load_directory(SIGNATURES_DIR)
+ assert total > 40 # stdlib + crypto
+
+ def test_lookup_exact(self):
+ db = SignatureDB()
+ db.load_file(SIGNATURES_DIR / "stdlib.json")
+ entry = db.lookup("malloc")
+ assert entry is not None
+ assert entry.name == "malloc"
+
+ def test_lookup_alias(self):
+ db = SignatureDB()
+ db.load_file(SIGNATURES_DIR / "stdlib.json")
+ entry = db.lookup("__libc_malloc")
+ assert entry is not None
+ assert entry.name == "malloc"
+
+ def test_lookup_normalized_underscores(self):
+ db = SignatureDB()
+ db.load_file(SIGNATURES_DIR / "stdlib.json")
+ # __memcpy -> stripped to memcpy
+ entry = db.lookup("__memcpy")
+ assert entry is not None
+ assert entry.name == "memcpy"
+
+ def test_lookup_case_insensitive(self):
+ db = SignatureDB()
+ db.load_file(SIGNATURES_DIR / "stdlib.json")
+ entry = db.lookup("MALLOC")
+ assert entry is not None
+ assert entry.name == "malloc"
+
+ def test_lookup_miss(self):
+ db = SignatureDB()
+ db.load_file(SIGNATURES_DIR / "stdlib.json")
+ assert db.lookup("my_custom_function") is None
+
+ def test_match_functions(self):
+ db = SignatureDB()
+ db.load_file(SIGNATURES_DIR / "stdlib.json")
+ funcs = [
+ _func(0x1000, "malloc"),
+ _func(0x2000, "FUN_00002000"), # no match
+ _func(0x3000, "strlen"),
+ ]
+ matches = db.match_functions(funcs)
+ assert len(matches) == 2
+ names = {m.matched_name for m in matches}
+ assert names == {"malloc", "strlen"}
+
+ def test_crypto_constants(self):
+ db = SignatureDB()
+ db.load_file(SIGNATURES_DIR / "crypto.json")
+ entry = db.lookup("sha256_init")
+ assert entry is not None
+ assert "0x6a09e667" in entry.indicators["constants"]
+
+ def test_load_nonexistent_file(self):
+ db = SignatureDB()
+ count = db.load_file(Path("/nonexistent/file.json"))
+ assert count == 0
+
+
+# ── TriageAgent ──────────────────────────────────────────────
+
+
+class TestTriageAgent:
+ def test_run_returns_triage_result(self):
+ funcs = [_func(0x1000, "a"), _func(0x2000, "b")]
+ client = _make_client(functions=funcs)
+ triage = TriageAgent(client)
+ result = triage.run()
+
+ assert isinstance(result, TriageResult)
+ assert result.total_functions == 2
+ assert isinstance(result.call_graph, CallGraph)
+ assert isinstance(result.queue, object)
+
+ def test_call_graph_built(self):
+ funcs = [_func(0x1000, "a"), _func(0x2000, "b")]
+ client = _make_client(functions=funcs)
+ client.get_callees.side_effect = lambda addr: [0x2000] if addr == 0x1000 else []
+ client.get_callers.side_effect = lambda addr: [0x1000] if addr == 0x2000 else []
+
+ triage = TriageAgent(client)
+ result = triage.run()
+
+ assert result.call_graph.callees[0x1000] == [0x2000]
+ assert result.call_graph.callers[0x2000] == [0x1000]
+
+ def test_signature_matching(self):
+ funcs = [_func(0x1000, "malloc"), _func(0x2000, "my_func")]
+ client = _make_client(functions=funcs)
+ db = SignatureDB()
+ db.load_file(SIGNATURES_DIR / "stdlib.json")
+
+ triage = TriageAgent(client, signature_db=db)
+ result = triage.run()
+
+ assert result.matched_count == 1
+ assert result.signature_matches[0].matched_name == "malloc"
+
+ def test_queue_built_with_correct_size(self):
+ funcs = [
+ _func(0x1000, "a"),
+ _func(0x2000, "b", cls=FunctionClassification.THUNK),
+ _func(0x3000, "c"),
+ ]
+ client = _make_client(functions=funcs)
+ triage = TriageAgent(client)
+ result = triage.run()
+
+ # Thunks excluded from queue
+ assert result.queue_size == 2
+
+
+# ── Language Detection ───────────────────────────────────────
+
+
+class TestLanguageDetection:
+ def test_detect_go(self):
+ funcs = [
+ _func(0x1000, "runtime.newproc"),
+ _func(0x2000, "runtime.goexit"),
+ _func(0x3000, "main.main"),
+ ]
+ client = _make_client(functions=funcs)
+ triage = TriageAgent(client)
+ result = triage.run()
+
+ assert result.language_hints.language == "Go"
+
+ def test_detect_rust(self):
+ funcs = [
+ _func(0x1000, "_ZN4core3ptr17h8a2e1234abcdef00E"),
+ _func(0x2000, "some_func"),
+ ]
+ client = _make_client(functions=funcs)
+ triage = TriageAgent(client)
+ result = triage.run()
+
+ assert result.language_hints.language == "Rust"
+
+ def test_detect_cpp(self):
+ funcs = [
+ _func(0x1000, "_ZN5MyApp4initEv"),
+ _func(0x2000, "_ZSt4cout"),
+ ]
+ client = _make_client(functions=funcs)
+ triage = TriageAgent(client)
+ result = triage.run()
+
+ assert result.language_hints.language == "C++"
+
+ def test_detect_cpp_from_vtable_strings(self):
+ funcs = [_func(0x1000, "func_a")]
+ strings = [StringEntry(address=0x5000, value="vtable for MyClass")]
+ client = _make_client(functions=funcs, strings=strings)
+ triage = TriageAgent(client)
+ result = triage.run()
+
+ assert result.language_hints.language == "C++"
+
+ def test_detect_c_default(self):
+ funcs = [_func(0x1000, "func_a"), _func(0x2000, "func_b")]
+ client = _make_client(functions=funcs)
+ triage = TriageAgent(client)
+ result = triage.run()
+
+ assert result.language_hints.language == "C"
+
+ def test_detect_compiler_from_strings(self):
+ funcs = [_func(0x1000, "a")]
+ strings = [StringEntry(address=0x5000, value="GCC: (Ubuntu 12.2) 12.2.0")]
+ client = _make_client(functions=funcs, strings=strings)
+ triage = TriageAgent(client)
+ result = triage.run()
+
+ assert result.language_hints.compiler == "GCC"
+
+
+class TestCallGraph:
+ def test_edge_count(self):
+ g = CallGraph(
+ callers={0x1000: [], 0x2000: [0x1000]},
+ callees={0x1000: [0x2000], 0x2000: []},
+ )
+ assert g.edge_count == 1
+
+ def test_empty_graph(self):
+ g = CallGraph()
+ assert g.edge_count == 0
+
+
+class TestTriageResultCounts:
+ def test_classification_counts(self):
+ result = TriageResult(
+ binary_info=BinaryInfo(arch="x86", format="ELF", endianness="little", word_size=8),
+ functions=[
+ _func(1, "a", cls=FunctionClassification.SMALL),
+ _func(2, "b", cls=FunctionClassification.SMALL),
+ _func(3, "c", cls=FunctionClassification.LARGE),
+ _func(4, "d", cls=FunctionClassification.THUNK),
+ ],
+ strings=[],
+ call_graph=CallGraph(),
+ signature_matches=[],
+ language_hints=LanguageHints(),
+ queue=MagicMock(total=3),
+ )
+ counts = result.classification_counts()
+ assert counts["small"] == 2
+ assert counts["large"] == 1
+ assert counts["thunk"] == 1