Skip to content

armgit / kong

Public Imported from GitHub
0

The world's first agentic reverse engineer.

Integrate LLM analysis into supervisor agent

Amruthdf9977eb6ecd
diff --git a/kong/__main__.py b/kong/__main__.py
index 9eb59df..5fea1d8 100644
--- a/kong/__main__.py
+++ b/kong/__main__.py
@@ -9,10 +9,13 @@ from rich.console import Console
from rich.markup import escape
from kong import __version__
-from kong.config import GhidraConfig, KongConfig, OutputConfig
+from collections import Counter
+from kong.agent.events import Event, EventType
+from kong.agent.supervisor import Supervisor
+from kong.config import GhidraConfig, KongConfig, OutputConfig
from kong.ghidra.client import GhidraClient, GhidraClientError
-from collections import Counter
+from kong.llm.client import AnthropicClient
console = Console()
@@ -94,22 +97,45 @@ def analyze(
console.print(f"[red]Failed to open binary:[/red] {escape(str(e))}")
raise SystemExit(1)
- # Get binary info
info = client.get_binary_info()
console.print(f"[green]Loaded.[/green] {info.arch} {info.format} ({info.compiler})")
- # Enumerate functions
- functions = client.list_functions()
- thunks = sum(1 for f in functions if f.is_thunk)
- console.print(
- f"Functions: {len(functions)} total, {thunks} thunks, "
- f"{len(functions) - thunks} to analyze"
- )
+ llm_client = AnthropicClient(api_key=""ANTHROPIC_API_KEY"")
+
+ def print_event(event: Event) -> None:
+ style = {
+ EventType.PHASE_START: "bold cyan",
+ EventType.PHASE_COMPLETE: "bold green",
+ EventType.FUNCTION_COMPLETE: "green",
+ EventType.FUNCTION_SKIPPED: "dim",
+ EventType.FUNCTION_ERROR: "red",
+ EventType.RUN_ERROR: "bold red",
+ EventType.RUN_COMPLETE: "bold green",
+ }.get(event.type, "")
+ if style:
+ console.print(f"[{style}]{escape(event.message)}[/{style}]")
+ else:
+ console.print(escape(event.message))
+
+ supervisor = Supervisor(client, config, llm_client=llm_client)
+ supervisor.on_event(print_event)
- # TODO: agent loop
- console.print("\n[yellow]done")
-
- client.close()
+ try:
+ supervisor.run()
+ except KeyboardInterrupt:
+ console.print("\n[yellow]Interrupted.[/yellow]")
+ finally:
+ stats = supervisor.stats
+ console.print()
+ console.print(f"[bold]Results:[/bold] {stats.named}/{stats.total_functions} functions named")
+ console.print(
+ f"[bold]Confidence:[/bold] {stats.high_confidence} high, "
+ f"{stats.medium_confidence} med, {stats.low_confidence} low"
+ )
+ console.print(f"[bold]LLM calls:[/bold] {stats.llm_calls}")
+ console.print(f"[bold]Cost:[/bold] ${llm_client.total_cost_usd:.4f}")
+ console.print(f"[bold]Duration:[/bold] {stats.duration_seconds:.1f}s")
+ client.close()
@cli.command()
diff --git a/kong/agent/analyzer.py b/kong/agent/analyzer.py
index 14516e4..54fbfb6 100644
--- a/kong/agent/analyzer.py
+++ b/kong/agent/analyzer.py
@@ -277,24 +277,6 @@ class Analyzer:
for addr, name in sorted(context.known_functions.items()):
parts.append(f"- 0x{addr:08x}: {name}")
- parts.append("")
- parts.append("### Instructions")
- parts.append(
- "Analyze the target function. Respond with a JSON object:\n"
- "```json\n"
- "{\n"
- ' "name": "descriptive_function_name",\n'
- ' "signature": "return_type name(param_type param_name, ...)",\n'
- ' "confidence": <0-100>,\n'
- ' "classification": "one of: crypto, networking, io, memory, '
- 'string, math, init, cleanup, handler, parser, utility, unknown",\n'
- ' "comments": "Brief description of what the function does",\n'
- ' "reasoning": "Why you chose this name and classification",\n'
- ' "variables": [{"old_name": "var1", "new_name": "descriptive_name"}]\n'
- "}\n"
- "```"
- )
-
return "\n".join(parts)
def _write_back(self, addr: int, response: LLMResponse) -> None:
diff --git a/kong/agent/events.py b/kong/agent/events.py
index bd615a6..4958c56 100644
--- a/kong/agent/events.py
+++ b/kong/agent/events.py
@@ -2,11 +2,12 @@
from __future__ import annotations
+from collections.abc import Callable
from dataclasses import dataclass, field
from enum import Enum
-from typing import Any, Callable
+from typing import Any
+
-# We opt for an event-based state machine approach here.
class Phase(Enum):
TRIAGE = "triage"
ANALYSIS = "analysis"
diff --git a/kong/agent/prompts.py b/kong/agent/prompts.py
new file mode 100644
index 0000000..2ae1dc3
--- /dev/null
+++ b/kong/agent/prompts.py
@@ -0,0 +1,39 @@
+"""Prompt templates for the analysis LLM."""
+
+from __future__ import annotations
+
+SYSTEM_PROMPT = """\
+You are an expert reverse engineer analyzing stripped binaries. You are given \
+decompiled C code from Ghidra and must determine what each function does.
+
+Your analysis must be precise:
+- Name functions based on what they actually do, not what they might do
+- Use standard naming conventions (snake_case for C, camelCase only if the binary is C++)
+- If you cannot determine a function's purpose, say so — do not guess
+- Confidence reflects how certain you are, not how important the function is
+
+You respond only with a JSON object. No prose before or after."""
+
+OUTPUT_SCHEMA = """\
+Respond with exactly one JSON object:
+```json
+{
+ "name": "descriptive_function_name",
+ "signature": "return_type name(param_type param_name, ...)",
+ "confidence": <0-100>,
+ "classification": "<category>",
+ "comments": "Brief description of what the function does",
+ "reasoning": "Why you chose this name and classification",
+ "variables": [{"old_name": "local_10", "new_name": "buffer"}]
+}
+```
+
+Classification must be one of: crypto, networking, io, memory, string, math, \
+init, cleanup, handler, parser, utility, unknown.
+
+Confidence guidelines:
+- 90-100: You recognize this exact algorithm or pattern (e.g., RC4, quicksort)
+- 70-89: Strong structural evidence for the name (clear string refs, API calls)
+- 50-69: Reasonable inference from context but multiple interpretations possible
+- 30-49: Educated guess based on limited evidence
+- 0-29: Very uncertain, minimal evidence"""
diff --git a/kong/agent/signatures.py b/kong/agent/signatures.py
index 629edb6..d336909 100644
--- a/kong/agent/signatures.py
+++ b/kong/agent/signatures.py
@@ -11,6 +11,10 @@ import json
import logging
from dataclasses import dataclass, field
from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from kong.ghidra.types import FunctionInfo
logger = logging.getLogger(__name__)
@@ -24,7 +28,7 @@ class SignatureEntry:
description: str = ""
signature: str = ""
category: str = "" # e.g., "stdlib", "crypto"
- indicators: dict = field(default_factory=dict)
+ indicators: dict[str, str | list[str]] = field(default_factory=dict)
@dataclass
@@ -108,7 +112,7 @@ class SignatureDB:
def match_functions(
self,
- functions: list, # list[FunctionInfo]
+ functions: list[FunctionInfo],
) -> list[SignatureMatch]:
"""Match a list of functions against the signature database.
diff --git a/kong/agent/supervisor.py b/kong/agent/supervisor.py
index 776c0e1..aae685a 100644
--- a/kong/agent/supervisor.py
+++ b/kong/agent/supervisor.py
@@ -17,7 +17,7 @@ from kong.agent.signatures import SignatureDB
from kong.agent.triage import TriageAgent, TriageResult
from kong.config import KongConfig
from kong.ghidra.client import GhidraClient
-from kong.ghidra.types import BinaryInfo, FunctionInfo
+from kong.ghidra.types import BinaryInfo, FunctionInfo, StringEntry
@dataclass
@@ -92,7 +92,7 @@ class Supervisor:
self.triage_result: TriageResult | None = None
self.binary_info: BinaryInfo | None = None
self.functions: list[FunctionInfo] = []
- self.strings: list = []
+ self.strings: list[StringEntry] = []
self._listeners: list[EventCallback] = []
self._paused: bool = False
@@ -356,7 +356,7 @@ class Supervisor:
))
- def _stats_dict(self) -> dict:
+ def _stats_dict(self) -> dict[str, int | float]:
s = self.stats
return {
"total_functions": s.total_functions,