The world's first agentic reverse engineer.
implement triage agent and analyzer (pre llm call)
Amruthb2e827c51aee
diff --git a/kong/agent/__init__.py b/kong/agent/__init__.pyindex 3c86e70..1adc5c9 100644--- a/kong/agent/__init__.py+++ b/kong/agent/__init__.py@@ -1,16 +1,29 @@"""Agent core — autonomous analysis pipeline."""+from kong.agent.analyzer import Analyzer, LLMClient, LLMResponsefrom kong.agent.events import Event, EventType, Phase+from kong.agent.models import FunctionResultfrom kong.agent.queue import WorkItem, WorkQueue-from kong.agent.supervisor import AnalysisStats, FunctionResult, Supervisor+from kong.agent.signatures import SignatureDB, SignatureMatch+from kong.agent.supervisor import AnalysisStats, Supervisor+from kong.agent.triage import CallGraph, LanguageHints, TriageAgent, TriageResult__all__ = [+ "AnalysisStats",+ "Analyzer",+ "CallGraph","Event","EventType",+ "FunctionResult",+ "LLMClient",+ "LLMResponse",+ "LanguageHints","Phase",+ "SignatureDB",+ "SignatureMatch",+ "Supervisor",+ "TriageAgent",+ "TriageResult","WorkItem","WorkQueue",- "AnalysisStats",- "FunctionResult",- "Supervisor",]diff --git a/kong/agent/analyzer.py b/kong/agent/analyzer.pynew file mode 100644index 0000000..14516e4--- /dev/null+++ b/kong/agent/analyzer.py@@ -0,0 +1,361 @@+"""Analyzer agent.++Takes a work item, gathers context, sends to the LLM, parses the+structured response, writes changes back to Ghidra, and returns+a FunctionResult.+"""++from __future__ import annotations++import json+import logging+from dataclasses import dataclass, field+from typing import Protocol++from kong.agent.models import FunctionResult+from kong.agent.queue import WorkItem+from kong.ghidra.client import GhidraClient+from kong.ghidra.types import BinaryInfo, FunctionInfo, StringEntry++logger = logging.getLogger(__name__)+++class LLMClient(Protocol):+ """Protocol for LLM interaction.++ TODO: add concrete implementation that uses Anthropic SDK.+ """++ def analyze_function(self, prompt: str) -> LLMResponse: ...+++@dataclass+class LLMResponse:+ """Structured response from the LLM for a single function analysis."""+ name: str+ signature: str = ""+ confidence: int = 0+ classification: str = ""+ comments: str = ""+ reasoning: str = ""+ variables: list[VariableRename] = field(default_factory=list)+ raw: str = ""+ input_tokens: int = 0+ output_tokens: int = 0+++@dataclass+class VariableRename:+ old_name: str+ new_name: str+++@dataclass+class AnalysisContext:+ """All context assembled for analyzing a single function."""+ function: FunctionInfo+ decompilation: str+ binary_info: BinaryInfo+ caller_snippets: list[CallerSnippet] = field(default_factory=list)+ callee_snippets: list[CalleeSnippet] = field(default_factory=list)+ referenced_strings: list[str] = field(default_factory=list)+ known_functions: dict[int, str] = field(default_factory=dict)+++@dataclass+class CallerSnippet:+ address: int+ name: str+ snippet: str+++@dataclass+class CalleeSnippet:+ address: int+ name: str+ snippet: str+++class Analyzer:+ """Analyzes a single function: gather context → LLM → parse → write back.++ Usage:+ analyzer = Analyzer(ghidra_client, llm_client)+ result = analyzer.analyze(work_item, binary_info, known_results, strings)+ """++ def __init__(+ self,+ client: GhidraClient,+ llm_client: LLMClient,+ ) -> None:+ self.client = client+ self.llm = llm_client++ def analyze(+ self,+ item: WorkItem,+ binary_info: BinaryInfo,+ known_results: dict[int, FunctionResult],+ strings: list[StringEntry],+ ) -> FunctionResult:+ """Full analysis pipeline for one function."""+ func = item.function++ context = self._build_context(item, binary_info, known_results, strings)+ prompt = self._build_prompt(context)++ response = self.llm.analyze_function(prompt)+ # TODO: validation?+ # TODO: error handling?+ # TODO: track token usage?++ self._write_back(func.address, response)++ return FunctionResult(+ address=func.address,+ original_name=func.name,+ name=response.name,+ signature=response.signature,+ confidence=response.confidence,+ classification=response.classification,+ comments=response.comments,+ reasoning=response.reasoning,+ llm_calls=1,+ )++ def _build_context(+ self,+ item: WorkItem,+ binary_info: BinaryInfo,+ known_results: dict[int, FunctionResult],+ strings: list[StringEntry],+ ) -> AnalysisContext:+ """Assemble all context the LLM needs to analyze this function."""+ func = item.function++ decompilation = self.client.get_decompilation(func.address)++ caller_snippets = self._get_caller_snippets(item.callers, known_results)+ callee_snippets = self._get_callee_snippets(item.callees, known_results)++ func_strings = self._get_referenced_strings(func.address, strings)++ known_map = {+ addr: r.name+ for addr, r in known_results.items()+ if r.name and not r.skipped and not r.error+ }++ return AnalysisContext(+ function=func,+ decompilation=decompilation,+ binary_info=binary_info,+ caller_snippets=caller_snippets,+ callee_snippets=callee_snippets,+ referenced_strings=func_strings,+ known_functions=known_map,+ )++ def _get_caller_snippets(+ self,+ caller_addrs: list[int],+ known_results: dict[int, FunctionResult],+ ) -> list[CallerSnippet]:+ """Get decompilation snippets for callers (first N lines each)."""+ snippets = []+ for addr in caller_addrs[:3]:+ name = self._resolve_name(addr, known_results)+ try:+ full = self.client.get_decompilation(addr)+ lines = full.split("\n")[:10]+ snippet = "\n".join(lines)+ except Exception:+ snippet = ""+ if snippet:+ snippets.append(CallerSnippet(address=addr, name=name, snippet=snippet))+ return snippets++ def _get_callee_snippets(+ self,+ callee_addrs: list[int],+ known_results: dict[int, FunctionResult],+ ) -> list[CalleeSnippet]:+ """Get decompilation snippets for callees (first N lines each)."""+ snippets = []+ for addr in callee_addrs[:5]:+ name = self._resolve_name(addr, known_results)+ try:+ full = self.client.get_decompilation(addr)+ lines = full.split("\n")[:10]+ snippet = "\n".join(lines)+ except Exception:+ snippet = ""+ if snippet:+ snippets.append(CalleeSnippet(address=addr, name=name, snippet=snippet))+ return snippets++ def _resolve_name(self, addr: int, known_results: dict[int, FunctionResult]) -> str:+ if addr in known_results and known_results[addr].name:+ return known_results[addr].name+ try:+ info = self.client.get_function_info(addr)+ return info.name+ except Exception:+ return f"FUN_{addr:08x}"++ def _get_referenced_strings(+ self,+ func_addr: int,+ strings: list[StringEntry],+ ) -> list[str]:+ """Find strings referenced by this function."""+ try:+ xrefs = self.client.get_xrefs_from(func_addr)+ ref_addrs = {x.to_addr for x in xrefs}+ except Exception:+ return []++ result = []+ for s in strings:+ if s.address in ref_addrs:+ result.append(s.value)+ return result++ def _build_prompt(self, context: AnalysisContext) -> str:+ """Build the LLM prompt from analysis context.++ The prompt structure is intentionally simple: present the+ decompilation and available context, ask for structured JSON output.++ TODO: refine prompt engineering from eval results.+ """+ parts = []++ parts.append(+ f"Binary: {context.binary_info.arch} {context.binary_info.format} "+ f"({context.binary_info.compiler})"+ )+ parts.append("")++ parts.append(f"## Target Function: {context.function.name} "+ f"(0x{context.function.address:08x})")+ parts.append(f"Size: {context.function.size} bytes")+ parts.append("")+ parts.append("### Decompilation")+ parts.append("```c")+ parts.append(context.decompilation)+ parts.append("```")++ if context.referenced_strings:+ parts.append("")+ parts.append("### Referenced Strings")+ for s in context.referenced_strings:+ parts.append(f'- "{s}"')++ if context.callee_snippets:+ parts.append("")+ parts.append("### Called Functions")+ for cs in context.callee_snippets:+ parts.append(f"#### {cs.name} (0x{cs.address:08x})")+ parts.append("```c")+ parts.append(cs.snippet)+ parts.append("```")++ if context.caller_snippets:+ parts.append("")+ parts.append("### Calling Functions")+ for cs in context.caller_snippets:+ parts.append(f"#### {cs.name} (0x{cs.address:08x})")+ parts.append("```c")+ parts.append(cs.snippet)+ parts.append("```")++ if context.known_functions:+ parts.append("")+ parts.append("### Already Identified Functions")+ 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:+ """Write analysis results back to Ghidra."""+ if response.name:+ try:+ self.client.rename_function(addr, response.name)+ except Exception as e:+ logger.warning("Failed to rename 0x%08x to %s: %s", addr, response.name, e)++ if response.signature:+ try:+ self.client.set_function_signature(addr, response.signature)+ except Exception as e:+ logger.warning("Failed to set signature at 0x%08x: %s", addr, e)++ if response.comments:+ try:+ self.client.add_comment(addr, response.comments)+ except Exception as e:+ logger.warning("Failed to add comment at 0x%08x: %s", addr, e)++ @staticmethod+ def parse_llm_json(raw: str) -> LLMResponse:+ """Parse the LLM's JSON response into an LLMResponse.++ Handles common issues: markdown fences, trailing commas, etc.+ """+ text = raw.strip()++ if "```json" in text:+ start = text.index("```json") + 7+ end = text.index("```", start)+ text = text[start:end].strip()+ elif "```" in text:+ start = text.index("```") + 3+ end = text.index("```", start)+ text = text[start:end].strip()++ try:+ data = json.loads(text)+ except json.JSONDecodeError:+ return LLMResponse(+ name="",+ reasoning=f"Failed to parse LLM response as JSON: {raw[:200]}",+ raw=raw,+ )++ variables = [+ VariableRename(old_name=v["old_name"], new_name=v["new_name"])+ for v in data.get("variables", [])+ if "old_name" in v and "new_name" in v+ ]++ return LLMResponse(+ name=data.get("name", ""),+ signature=data.get("signature", ""),+ confidence=data.get("confidence", 0),+ classification=data.get("classification", ""),+ comments=data.get("comments", ""),+ reasoning=data.get("reasoning", ""),+ variables=variables,+ raw=raw,+ )diff --git a/kong/agent/models.py b/kong/agent/models.pynew file mode 100644index 0000000..e9707a6--- /dev/null+++ b/kong/agent/models.py@@ -0,0 +1,22 @@+"""Shared data models for the agent pipeline."""++from __future__ import annotations++from dataclasses import dataclass+++@dataclass+class FunctionResult:+ """Result of analyzing a single function."""+ address: int+ original_name: str+ name: str = ""+ signature: str = ""+ confidence: int = 0+ classification: str = ""+ comments: str = ""+ reasoning: str = ""+ error: str = ""+ llm_calls: int = 0+ skipped: bool = False+ skip_reason: str = ""diff --git a/kong/agent/signatures.py b/kong/agent/signatures.pynew file mode 100644index 0000000..629edb6--- /dev/null+++ b/kong/agent/signatures.py@@ -0,0 +1,139 @@+"""Signature db for matching known library functions.++Loads JSON signature files and matches function names/aliases against them.+This matches Ghidra's auto-detected import names and symbol names against known signatures.+Constants-based and pattern-based matching is handled by the LLM during analysis.+"""++from __future__ import annotations++import json+import logging+from dataclasses import dataclass, field+from pathlib import Path++logger = logging.getLogger(__name__)++SIGNATURES_DIR = Path(__file__).parent.parent / "signatures"+++@dataclass+class SignatureEntry:+ name: str+ aliases: list[str] = field(default_factory=list)+ description: str = ""+ signature: str = ""+ category: str = "" # e.g., "stdlib", "crypto"+ indicators: dict = field(default_factory=dict)+++@dataclass+class SignatureMatch:+ """A match between a function and a known signature."""+ function_address: int+ function_name: str+ matched_name: str # canonical name from DB+ signature: str+ category: str+ description: str+++class SignatureDB:+ """In-memory signature database loaded from JSON files.++ Provides fast name-based lookup via a normalized name index.+ """++ def __init__(self) -> None:+ self._entries: list[SignatureEntry] = []+ self._name_index: dict[str, SignatureEntry] = {} # normalized name -> entry++ @staticmethod+ def _normalize(name: str) -> str:+ """Normalize a function name for matching.++ Strips leading underscores and lowercases, so that+ __memcpy, _memcpy, MEMCPY all match memcpy.+ """+ return name.lstrip("_").lower()++ def load_file(self, path: Path, category: str = "") -> int:+ """Load signatures from a JSON file. Returns count loaded."""+ if not path.exists():+ logger.warning("Signature file not found: %s", path)+ return 0++ with open(path) as f:+ data = json.load(f)++ count = 0+ for item in data:+ entry = SignatureEntry(+ name=item["name"],+ aliases=item.get("aliases", []),+ description=item.get("description", ""),+ signature=item.get("signature", ""),+ category=category or path.stem,+ indicators=item.get("indicators", {}),+ )+ self._entries.append(entry)++ # Index by normalized canonical name and all aliases+ for name in [entry.name] + entry.aliases:+ self._name_index[self._normalize(name)] = entry+ count += 1++ return count++ def load_directory(self, directory: Path | None = None) -> int:+ """Load all .json files from a directory. Returns total count."""+ if directory is None:+ directory = SIGNATURES_DIR++ if not directory.is_dir():+ logger.warning("Signatures directory not found: %s", directory)+ return 0++ total = 0+ for path in sorted(directory.glob("*.json")):+ loaded = self.load_file(path, category=path.stem)+ logger.info("Loaded %d signatures from %s", loaded, path.name)+ total += loaded++ return total++ def lookup(self, name: str) -> SignatureEntry | None:+ """Look up a function name in the database."""+ return self._name_index.get(self._normalize(name))++ def match_functions(+ self,+ functions: list, # list[FunctionInfo]+ ) -> list[SignatureMatch]:+ """Match a list of functions against the signature database.++ Returns matches for functions whose names (as detected by Ghidra)+ match known signatures. This catches imported functions that Ghidra+ already identified by name.+ """+ matches = []+ for func in functions:+ entry = self.lookup(func.name)+ if entry is not None:+ matches.append(SignatureMatch(+ function_address=func.address,+ function_name=func.name,+ matched_name=entry.name,+ signature=entry.signature,+ category=entry.category,+ description=entry.description,+ ))+ return matches++ @property+ def size(self) -> int:+ return len(self._entries)++ @property+ def entries(self) -> list[SignatureEntry]:+ return list(self._entries)diff --git a/kong/agent/supervisor.py b/kong/agent/supervisor.pyindex 5e5ddd0..776c0e1 100644--- a/kong/agent/supervisor.py+++ b/kong/agent/supervisor.py@@ -9,30 +9,17 @@ from __future__ import annotationsimport timefrom dataclasses import dataclass+from kong.agent.analyzer import Analyzer, LLMClientfrom kong.agent.events import Event, EventCallback, EventType, Phase-from kong.agent.queue import WorkQueue+from kong.agent.models import FunctionResult+from kong.agent.queue import WorkItem, WorkQueue+from kong.agent.signatures import SignatureDB+from kong.agent.triage import TriageAgent, TriageResultfrom kong.config import KongConfigfrom kong.ghidra.client import GhidraClientfrom kong.ghidra.types import BinaryInfo, FunctionInfo-@dataclass-class FunctionResult:- """Result of analyzing a single function."""- address: int- original_name: str- name: str = ""- signature: str = ""- confidence: int = 0- classification: str = ""- comments: str = ""- reasoning: str = ""- error: str = ""- llm_calls: int = 0- skipped: bool = False- skip_reason: str = ""--@dataclassclass AnalysisStats:"""Aggregate statistics for the full run."""@@ -69,6 +56,8 @@ class AnalysisStats:self.llm_calls += result.llm_callsif result.name and result.name != result.original_name:self.named += 1+ # TODO: calibrate these eventually. these buckets are arbitrary, need eval data to+ # determine meaningful confidence tiers for the LLM's self-reported scores.if result.confidence >= 80:self.high_confidence += 1elif result.confidence >= 50:@@ -90,17 +79,22 @@ class Supervisor:self,client: GhidraClient,config: KongConfig,+ llm_client: LLMClient | None = None,+ signature_db: SignatureDB | None = None,) -> None:self.client = clientself.config = config+ self.llm_client = llm_client+ self.sig_db = signature_db or SignatureDB()self.queue = WorkQueue()self.stats = AnalysisStats()- self.results: dict[int, FunctionResult] = {} # Mapping of address to FunctionResult- self.binary_info: BinaryInfo | None = None # initially None until set in _run_triage- self.functions: list[FunctionInfo] = [] # empty until set in _run_triage- self.strings: list = [] # empty until set in _run_triage- self._listeners: list[EventCallback] = [] # empty until on_event is called- self._paused: bool = False # False until pause or resume is called+ self.results: dict[int, FunctionResult] = {}+ self.triage_result: TriageResult | None = None+ self.binary_info: BinaryInfo | None = None+ self.functions: list[FunctionInfo] = []+ self.strings: list = []+ self._listeners: list[EventCallback] = []+ self._paused: bool = Falsedef on_event(self, callback: EventCallback) -> None:"""Register an event listener."""@@ -157,9 +151,17 @@ class Supervisor:message="Starting triage...",))- self.binary_info = self.client.get_binary_info()- self.functions = self.client.list_functions()- self.strings = self.client.get_strings()+ triage = TriageAgent(self.client, signature_db=self.sig_db)+ result = triage.run()+ self.triage_result = result++ # propagate triage results to supervisor state+ self.binary_info = result.binary_info+ self.functions = result.functions+ self.strings = result.strings+ self.queue = result.queue+ self.stats.total_functions = result.queue_size+ self.stats.signature_matches = result.matched_countself._emit(Event(type=EventType.TRIAGE_FUNCTIONS_ENUMERATED,@@ -175,14 +177,6 @@ class Supervisor:},))- callers_map: dict[int, list[int]] = {}- callees_map: dict[int, list[int]] = {}- for func in self.functions:- addr = func.address- callers_map[addr] = self.client.get_callers(addr)- callees_map[addr] = self.client.get_callees(addr)-- # TODO: Match against signature DB.self._emit(Event(type=EventType.TRIAGE_SIGNATURES_MATCHED,phase=Phase.TRIAGE,@@ -190,9 +184,6 @@ class Supervisor:data={"matched": self.stats.signature_matches},))- self.queue.build(self.functions, callers_map, callees_map)- self.stats.total_functions = self.queue.total-self._emit(Event(type=EventType.TRIAGE_QUEUE_BUILT,phase=Phase.TRIAGE,@@ -203,6 +194,14 @@ class Supervisor:data={"queue_size": self.queue.total},))+ if result.language_hints.language != "C":+ self._emit(Event(+ type=EventType.PHASE_START,+ phase=Phase.TRIAGE,+ message=f"Detected language: {result.language_hints.language}",+ data={"language": result.language_hints.language},+ ))+self._emit(Event(type=EventType.PHASE_COMPLETE,phase=Phase.TRIAGE,@@ -288,12 +287,8 @@ class Supervisor:),))- def _analyze_function(self, item) -> FunctionResult:- """Analyze a single function. Delegates to the analyzer agent.-- TODO: Implement analyzer agent here.- This is the integration point where the analyzer agent will plug in.- """+ def _analyze_function(self, item: WorkItem) -> FunctionResult:+ """Analyze a single function. Delegates to the Analyzer agent."""func = item.functionif func.classification and func.classification.value == "trivial":@@ -304,14 +299,20 @@ class Supervisor:skip_reason="trivial",)- # TODO: analyzer agent something like- # analyzer = Analyzer(self.client, self.llm_client, self.config)- # return analyzer.analyze(item, context=self._build_context(item))- return FunctionResult(- address=func.address,- original_name=func.name,- name=func.name, # unchanged for now- confidence=0,+ if self.llm_client is None:+ return FunctionResult(+ address=func.address,+ original_name=func.name,+ name=func.name,+ confidence=0,+ )++ analyzer = Analyzer(self.client, self.llm_client)+ return analyzer.analyze(+ item,+ binary_info=self.binary_info,+ known_results=self.results,+ strings=self.strings,)def _run_cleanup(self) -> None:diff --git a/kong/agent/triage.py b/kong/agent/triage.pynew file mode 100644index 0000000..a51d109--- /dev/null+++ b/kong/agent/triage.py@@ -0,0 +1,189 @@+"""Triage agent.++Enumerates functions, matches signatures, detects compiler/language hints,+builds the call graph, and produces the ordered work queue.+"""++from __future__ import annotations++import logging+from dataclasses import dataclass, field++from kong.agent.queue import WorkQueue+from kong.agent.signatures import SignatureDB, SignatureMatch+from kong.ghidra.client import GhidraClient+from kong.ghidra.types import BinaryInfo, FunctionInfo, StringEntry++logger = logging.getLogger(__name__)+++@dataclass+class CallGraph:+ """Adjacency lists for the call graph."""+ callers: dict[int, list[int]] = field(default_factory=dict) # addr -> [caller addrs]+ callees: dict[int, list[int]] = field(default_factory=dict) # addr -> [callee addrs]++ @property+ def edge_count(self) -> int:+ return sum(len(v) for v in self.callees.values())+++@dataclass+class LanguageHints:+ """Detected language and compiler hints from binary analysis."""+ compiler: str = "unknown"+ language: str = "C" # C, C++, Go, Rust+ indicators: list[str] = field(default_factory=list)+++@dataclass+class TriageResult:+ """Complete output of the triage phase."""+ binary_info: BinaryInfo+ functions: list[FunctionInfo]+ strings: list[StringEntry]+ call_graph: CallGraph+ signature_matches: list[SignatureMatch]+ language_hints: LanguageHints+ queue: WorkQueue++ @property+ def total_functions(self) -> int:+ return len(self.functions)++ @property+ def matched_count(self) -> int:+ return len(self.signature_matches)++ @property+ def queue_size(self) -> int:+ return self.queue.total++ def classification_counts(self) -> dict[str, int]:+ counts: dict[str, int] = {}+ for f in self.functions:+ cls = f.classification.value if f.classification else "unknown"+ counts[cls] = counts.get(cls, 0) + 1+ return counts+++class TriageAgent:+ """Runs Phase 1: enumerate, classify, match, build queue.++ Usage:+ triage = TriageAgent(client)+ result = triage.run()+ # result.queue is ready for the analysis phase+ """++ def __init__(+ self,+ client: GhidraClient,+ signature_db: SignatureDB | None = None,+ ) -> None:+ self.client = client+ self.sig_db = signature_db or SignatureDB()++ def run(self) -> TriageResult:+ """Execute the full triage phase."""+ binary_info = self.client.get_binary_info()+ functions = self.client.list_functions()+ strings = self.client.get_strings()++ call_graph = self._build_call_graph(functions)+ signature_matches = self._match_signatures(functions)+ language_hints = self._detect_language(binary_info, functions, strings)+ queue = self._build_queue(functions, call_graph)++ return TriageResult(+ binary_info=binary_info,+ functions=functions,+ strings=strings,+ call_graph=call_graph,+ signature_matches=signature_matches,+ language_hints=language_hints,+ queue=queue,+ )++ def _build_call_graph(self, functions: list[FunctionInfo]) -> CallGraph:+ """Build caller/callee adjacency lists from Ghidra xrefs."""+ graph = CallGraph()+ for func in functions:+ addr = func.address+ graph.callers[addr] = self.client.get_callers(addr)+ graph.callees[addr] = self.client.get_callees(addr)+ return graph++ def _match_signatures(self, functions: list[FunctionInfo]) -> list[SignatureMatch]:+ """Match functions against the signature database."""+ if self.sig_db.size == 0:+ self.sig_db.load_directory()++ return self.sig_db.match_functions(functions)++ def _detect_language(+ self,+ binary_info: BinaryInfo,+ functions: list[FunctionInfo],+ strings: list[StringEntry],+ ) -> LanguageHints:+ """Detect compiler and source language from binary artifacts."""+ hints = LanguageHints(compiler=binary_info.compiler)+ names = {f.name for f in functions}+ string_values = {s.value for s in strings}++ # Go detection+ go_indicators = [+ n for n in names+ if n.startswith("runtime.") or n.startswith("main.main")+ ]+ if go_indicators:+ hints.language = "Go"+ hints.indicators.append(f"Go runtime functions: {len(go_indicators)}")++ # Rust detection+ rust_mangled = [n for n in names if "_ZN" in n and "17h" in n]+ if rust_mangled:+ hints.language = "Rust"+ hints.indicators.append(f"Rust mangled symbols: {len(rust_mangled)}")++ # C++ detection (if not Go/Rust)+ if hints.language == "C":+ cpp_indicators = [+ n for n in names+ if n.startswith("_ZN") or n.startswith("_ZSt") or n.startswith("std::")+ ]+ vtable_strings = [s for s in string_values if "vtable" in s.lower()]+ if cpp_indicators or vtable_strings:+ hints.language = "C++"+ if cpp_indicators:+ hints.indicators.append(f"C++ mangled symbols: {len(cpp_indicators)}")+ if vtable_strings:+ hints.indicators.append(f"vtable references: {len(vtable_strings)}")++ # Compiler hints from strings+ for s in string_values:+ if "GCC:" in s or "gcc" in s.lower():+ hints.compiler = "GCC"+ hints.indicators.append(f"GCC string: {s[:60]}")+ break+ if "clang" in s.lower():+ hints.compiler = "Clang"+ hints.indicators.append(f"Clang string: {s[:60]}")+ break++ return hints++ def _build_queue(+ self,+ functions: list[FunctionInfo],+ call_graph: CallGraph,+ ) -> WorkQueue:+ """Build the priority work queue from functions and call graph."""+ queue = WorkQueue()+ queue.build(+ functions,+ callers_map=call_graph.callers,+ callees_map=call_graph.callees,+ )+ return queuediff --git a/kong/signatures/crypto.json b/kong/signatures/crypto.jsonnew file mode 100644index 0000000..1715082--- /dev/null+++ b/kong/signatures/crypto.json@@ -0,0 +1,260 @@+[+ {+ "name": "rc4_init",+ "aliases": [+ "rc4_ksa",+ "arcfour_init",+ "arc4_init"+ ],+ "description": "RC4 Key Scheduling Algorithm",+ "indicators": {+ "constants": [+ "0x100"+ ],+ "patterns": [+ "256-iteration loop initializing sequential array, then swap loop using key bytes modulo keylen"+ ],+ "strings": []+ },+ "signature": "void rc4_init(uint8_t *state, const uint8_t *key, int keylen)"+ },+ {+ "name": "rc4_crypt",+ "aliases": [+ "rc4_encrypt",+ "rc4_decrypt",+ "arcfour_crypt",+ "arc4_crypt"+ ],+ "description": "RC4 stream cipher encrypt/decrypt (PRGA)",+ "indicators": {+ "constants": [+ "0xff"+ ],+ "patterns": [+ "state array swap with i,j indices, XOR output byte with data"+ ],+ "strings": []+ },+ "signature": "void rc4_crypt(uint8_t *state, uint8_t *data, int len)"+ },+ {+ "name": "aes_sbox_lookup",+ "aliases": [+ "aes_sub_bytes",+ "SubBytes"+ ],+ "description": "AES S-box substitution",+ "indicators": {+ "constants": [+ "0x63",+ "0x7c",+ "0x77",+ "0x7b",+ "0xf2",+ "0x6b",+ "0x6f",+ "0xc5"+ ],+ "patterns": [+ "256-byte lookup table with known AES S-box values"+ ],+ "strings": []+ },+ "signature": "void aes_sub_bytes(uint8_t *state)"+ },+ {+ "name": "aes_key_expansion",+ "aliases": [+ "AES_set_encrypt_key",+ "aes_expand_key",+ "KeyExpansion"+ ],+ "description": "AES key schedule expansion",+ "indicators": {+ "constants": [+ "0x01",+ "0x02",+ "0x04",+ "0x08",+ "0x10",+ "0x20",+ "0x40",+ "0x80",+ "0x1b",+ "0x36"+ ],+ "patterns": [+ "round constant (Rcon) array, RotWord, SubWord operations, XOR with previous round key"+ ],+ "strings": []+ },+ "signature": "void aes_key_expansion(const uint8_t *key, uint8_t *round_keys, int key_len)"+ },+ {+ "name": "sha256_init",+ "aliases": [+ "SHA256_Init",+ "sha256_start"+ ],+ "description": "SHA-256 initialization with standard IV",+ "indicators": {+ "constants": [+ "0x6a09e667",+ "0xbb67ae85",+ "0x3c6ef372",+ "0xa54ff53a",+ "0x510e527f",+ "0x9b05688c",+ "0x1f83d9ab",+ "0x5be0cd19"+ ],+ "patterns": [+ "sets 8 state words to SHA-256 initialization vectors"+ ],+ "strings": []+ },+ "signature": "void sha256_init(sha256_ctx *ctx)"+ },+ {+ "name": "sha256_transform",+ "aliases": [+ "SHA256_Transform",+ "sha256_compress",+ "sha256_process_block"+ ],+ "description": "SHA-256 compression function",+ "indicators": {+ "constants": [+ "0x428a2f98",+ "0x71374491",+ "0xb5c0fbcf",+ "0xe9b5dba5"+ ],+ "patterns": [+ "64-round loop with message schedule, Ch/Maj/Sigma operations"+ ],+ "strings": []+ },+ "signature": "void sha256_transform(uint32_t *state, const uint8_t *block)"+ },+ {+ "name": "md5_init",+ "aliases": [+ "MD5_Init",+ "MD5Init"+ ],+ "description": "MD5 initialization",+ "indicators": {+ "constants": [+ "0x67452301",+ "0xefcdab89",+ "0x98badcfe",+ "0x10325476"+ ],+ "patterns": [+ "sets 4 state words to MD5 initialization vectors"+ ],+ "strings": []+ },+ "signature": "void md5_init(md5_ctx *ctx)"+ },+ {+ "name": "md5_transform",+ "aliases": [+ "MD5_Transform",+ "MD5Transform",+ "md5_compress"+ ],+ "description": "MD5 compression function",+ "indicators": {+ "constants": [+ "0xd76aa478",+ "0xe8c7b756",+ "0x242070db",+ "0xc1bdceee"+ ],+ "patterns": [+ "64-step processing with F/G/H/I rounds, sine-derived constants"+ ],+ "strings": []+ },+ "signature": "void md5_transform(uint32_t *state, const uint8_t *block)"+ },+ {+ "name": "sha1_init",+ "aliases": [+ "SHA1_Init",+ "SHA1Init"+ ],+ "description": "SHA-1 initialization",+ "indicators": {+ "constants": [+ "0x67452301",+ "0xefcdab89",+ "0x98badcfe",+ "0x10325476",+ "0xc3d2e1f0"+ ],+ "patterns": [+ "sets 5 state words to SHA-1 initialization vectors"+ ],+ "strings": []+ },+ "signature": "void sha1_init(sha1_ctx *ctx)"+ },+ {+ "name": "crc32_update",+ "aliases": [+ "crc32",+ "crc32_byte"+ ],+ "description": "CRC-32 checksum update",+ "indicators": {+ "constants": [+ "0xedb88320"+ ],+ "patterns": [+ "256-entry lookup table or bit-by-bit with polynomial 0xedb88320"+ ],+ "strings": []+ },+ "signature": "uint32_t crc32_update(uint32_t crc, const uint8_t *data, size_t len)"+ },+ {+ "name": "base64_encode",+ "aliases": [+ "b64_encode",+ "EVP_EncodeBlock"+ ],+ "description": "Base64 encoding",+ "indicators": {+ "constants": [],+ "patterns": [+ "3-byte to 4-char conversion using alphabet lookup table"+ ],+ "strings": [+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"+ ]+ },+ "signature": "int base64_encode(const uint8_t *input, int input_len, char *output)"+ },+ {+ "name": "base64_decode",+ "aliases": [+ "b64_decode",+ "EVP_DecodeBlock"+ ],+ "description": "Base64 decoding",+ "indicators": {+ "constants": [],+ "patterns": [+ "4-char to 3-byte conversion using reverse lookup"+ ],+ "strings": [+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"+ ]+ },+ "signature": "int base64_decode(const char *input, int input_len, uint8_t *output)"+ }+]diff --git a/kong/signatures/stdlib.json b/kong/signatures/stdlib.jsonnew file mode 100644index 0000000..6edd955--- /dev/null+++ b/kong/signatures/stdlib.json@@ -0,0 +1,643 @@+[+ {+ "name": "memcpy",+ "aliases": [+ "__memcpy",+ "memmove_chk"+ ],+ "description": "Copy memory block",+ "indicators": {+ "constants": [],+ "patterns": [+ "byte-by-byte or word-by-word copy loop with source and destination pointers"+ ],+ "strings": []+ },+ "signature": "void *memcpy(void *dest, const void *src, size_t n)"+ },+ {+ "name": "memset",+ "aliases": [+ "__memset",+ "bzero"+ ],+ "description": "Fill memory with constant byte",+ "indicators": {+ "constants": [],+ "patterns": [+ "loop filling memory with single byte value, often used for zeroing"+ ],+ "strings": []+ },+ "signature": "void *memset(void *s, int c, size_t n)"+ },+ {+ "name": "memcmp",+ "aliases": [+ "__memcmp",+ "bcmp"+ ],+ "description": "Compare memory blocks",+ "indicators": {+ "constants": [],+ "patterns": [+ "byte-by-byte comparison loop with early return on mismatch"+ ],+ "strings": []+ },+ "signature": "int memcmp(const void *s1, const void *s2, size_t n)"+ },+ {+ "name": "strlen",+ "aliases": [+ "__strlen"+ ],+ "description": "Get string length",+ "indicators": {+ "constants": [],+ "patterns": [+ "loop scanning for null terminator byte"+ ],+ "strings": []+ },+ "signature": "size_t strlen(const char *s)"+ },+ {+ "name": "strcmp",+ "aliases": [+ "__strcmp"+ ],+ "description": "Compare two strings",+ "indicators": {+ "constants": [],+ "patterns": [+ "byte-by-byte comparison with null terminator check"+ ],+ "strings": []+ },+ "signature": "int strcmp(const char *s1, const char *s2)"+ },+ {+ "name": "strncmp",+ "aliases": [+ "__strncmp"+ ],+ "description": "Compare two strings with length limit",+ "indicators": {+ "constants": [],+ "patterns": [+ "byte-by-byte comparison with null terminator and counter check"+ ],+ "strings": []+ },+ "signature": "int strncmp(const char *s1, const char *s2, size_t n)"+ },+ {+ "name": "strcpy",+ "aliases": [+ "__strcpy",+ "strcpy_chk"+ ],+ "description": "Copy string",+ "indicators": {+ "constants": [],+ "patterns": [+ "byte copy loop until null terminator"+ ],+ "strings": []+ },+ "signature": "char *strcpy(char *dest, const char *src)"+ },+ {+ "name": "strncpy",+ "aliases": [+ "__strncpy",+ "strncpy_chk"+ ],+ "description": "Copy string with length limit",+ "indicators": {+ "constants": [],+ "patterns": [+ "byte copy loop with counter, null padding"+ ],+ "strings": []+ },+ "signature": "char *strncpy(char *dest, const char *src, size_t n)"+ },+ {+ "name": "strcat",+ "aliases": [+ "__strcat"+ ],+ "description": "Concatenate strings",+ "indicators": {+ "constants": [],+ "patterns": [+ "find end of dest string then copy src"+ ],+ "strings": []+ },+ "signature": "char *strcat(char *dest, const char *src)"+ },+ {+ "name": "strchr",+ "aliases": [+ "__strchr",+ "index"+ ],+ "description": "Find first occurrence of character in string",+ "indicators": {+ "constants": [],+ "patterns": [+ "scan string for character match, return pointer or NULL"+ ],+ "strings": []+ },+ "signature": "char *strchr(const char *s, int c)"+ },+ {+ "name": "strstr",+ "aliases": [+ "__strstr"+ ],+ "description": "Find substring",+ "indicators": {+ "constants": [],+ "patterns": [+ "nested loop: outer scans haystack, inner compares needle"+ ],+ "strings": []+ },+ "signature": "char *strstr(const char *haystack, const char *needle)"+ },+ {+ "name": "malloc",+ "aliases": [+ "__libc_malloc",+ "dlmalloc",+ "je_malloc"+ ],+ "description": "Allocate memory",+ "indicators": {+ "constants": [],+ "patterns": [+ "heap allocation with size parameter, returns pointer or NULL"+ ],+ "strings": []+ },+ "signature": "void *malloc(size_t size)"+ },+ {+ "name": "calloc",+ "aliases": [+ "__libc_calloc"+ ],+ "description": "Allocate and zero memory",+ "indicators": {+ "constants": [],+ "patterns": [+ "malloc-like with nmemb*size multiplication and zeroing"+ ],+ "strings": []+ },+ "signature": "void *calloc(size_t nmemb, size_t size)"+ },+ {+ "name": "realloc",+ "aliases": [+ "__libc_realloc"+ ],+ "description": "Reallocate memory block",+ "indicators": {+ "constants": [],+ "patterns": [+ "resize allocation, copy existing data, free old block"+ ],+ "strings": []+ },+ "signature": "void *realloc(void *ptr, size_t size)"+ },+ {+ "name": "free",+ "aliases": [+ "__libc_free",+ "cfree",+ "dlfree",+ "je_free"+ ],+ "description": "Free allocated memory",+ "indicators": {+ "constants": [],+ "patterns": [+ "heap deallocation, null check common"+ ],+ "strings": []+ },+ "signature": "void free(void *ptr)"+ },+ {+ "name": "printf",+ "aliases": [+ "__printf",+ "__printf_chk"+ ],+ "description": "Formatted output to stdout",+ "indicators": {+ "constants": [],+ "patterns": [+ "format string parsing with va_list, writes to stdout"+ ],+ "strings": []+ },+ "signature": "int printf(const char *format, ...)"+ },+ {+ "name": "fprintf",+ "aliases": [+ "__fprintf",+ "__fprintf_chk"+ ],+ "description": "Formatted output to stream",+ "indicators": {+ "constants": [],+ "patterns": [+ "format string parsing with va_list, writes to FILE*"+ ],+ "strings": []+ },+ "signature": "int fprintf(FILE *stream, const char *format, ...)"+ },+ {+ "name": "sprintf",+ "aliases": [+ "__sprintf",+ "__sprintf_chk"+ ],+ "description": "Formatted output to string buffer",+ "indicators": {+ "constants": [],+ "patterns": [+ "format string parsing, writes to char buffer"+ ],+ "strings": []+ },+ "signature": "int sprintf(char *str, const char *format, ...)"+ },+ {+ "name": "snprintf",+ "aliases": [+ "__snprintf",+ "__snprintf_chk"+ ],+ "description": "Formatted output to string buffer with size limit",+ "indicators": {+ "constants": [],+ "patterns": [+ "format string parsing with buffer size check"+ ],+ "strings": []+ },+ "signature": "int snprintf(char *str, size_t size, const char *format, ...)"+ },+ {+ "name": "puts",+ "aliases": [+ "_IO_puts"+ ],+ "description": "Write string to stdout with newline",+ "indicators": {+ "constants": [],+ "patterns": [+ "write string followed by newline to stdout"+ ],+ "strings": []+ },+ "signature": "int puts(const char *s)"+ },+ {+ "name": "fopen",+ "aliases": [+ "fopen64",+ "_IO_fopen"+ ],+ "description": "Open file",+ "indicators": {+ "constants": [],+ "patterns": [+ "path string + mode string, returns FILE pointer"+ ],+ "strings": []+ },+ "signature": "FILE *fopen(const char *pathname, const char *mode)"+ },+ {+ "name": "fclose",+ "aliases": [+ "_IO_fclose"+ ],+ "description": "Close file",+ "indicators": {+ "constants": [],+ "patterns": [+ "flush buffer, release FILE structure"+ ],+ "strings": []+ },+ "signature": "int fclose(FILE *stream)"+ },+ {+ "name": "fread",+ "aliases": [+ "_IO_fread"+ ],+ "description": "Read from file",+ "indicators": {+ "constants": [],+ "patterns": [+ "read size*nmemb bytes from stream into buffer"+ ],+ "strings": []+ },+ "signature": "size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)"+ },+ {+ "name": "fwrite",+ "aliases": [+ "_IO_fwrite"+ ],+ "description": "Write to file",+ "indicators": {+ "constants": [],+ "patterns": [+ "write size*nmemb bytes from buffer to stream"+ ],+ "strings": []+ },+ "signature": "size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)"+ },+ {+ "name": "atoi",+ "aliases": [+ "__atoi"+ ],+ "description": "Convert string to integer",+ "indicators": {+ "constants": [+ "0x30"+ ],+ "patterns": [+ "skip whitespace, handle sign, accumulate digits"+ ],+ "strings": []+ },+ "signature": "int atoi(const char *nptr)"+ },+ {+ "name": "strtol",+ "aliases": [+ "strtol_l",+ "__strtol_internal"+ ],+ "description": "Convert string to long integer",+ "indicators": {+ "constants": [],+ "patterns": [+ "skip whitespace, handle sign and base prefix, accumulate digits with overflow check"+ ],+ "strings": []+ },+ "signature": "long strtol(const char *nptr, char **endptr, int base)"+ },+ {+ "name": "exit",+ "aliases": [+ "_exit",+ "__exit",+ "_Exit"+ ],+ "description": "Terminate process",+ "indicators": {+ "constants": [],+ "patterns": [+ "atexit handler chain, flush streams, syscall exit_group"+ ],+ "strings": []+ },+ "signature": "void exit(int status)"+ },+ {+ "name": "abort",+ "aliases": [+ "__abort"+ ],+ "description": "Abnormal termination",+ "indicators": {+ "constants": [+ "6"+ ],+ "patterns": [+ "raise SIGABRT, noreturn"+ ],+ "strings": []+ },+ "signature": "void abort(void)"+ },+ {+ "name": "qsort",+ "aliases": [+ "__qsort"+ ],+ "description": "Sort array",+ "indicators": {+ "constants": [],+ "patterns": [+ "comparison function pointer callback, pivot selection, partitioning"+ ],+ "strings": []+ },+ "signature": "void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *))"+ },+ {+ "name": "bsearch",+ "aliases": [+ "__bsearch"+ ],+ "description": "Binary search sorted array",+ "indicators": {+ "constants": [],+ "patterns": [+ "divide-and-conquer with comparison callback, lo/hi/mid pattern"+ ],+ "strings": []+ },+ "signature": "void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *))"+ },+ {+ "name": "__stack_chk_fail",+ "aliases": [+ "__stack_smash_handler"+ ],+ "description": "Stack canary check failure handler",+ "indicators": {+ "constants": [],+ "patterns": [+ "noreturn, called when stack canary mismatch detected"+ ],+ "strings": [+ "stack smashing detected",+ "*** stack smashing"+ ]+ },+ "signature": "void __stack_chk_fail(void)"+ },+ {+ "name": "__libc_start_main",+ "aliases": [+ "__libc_start_call_main"+ ],+ "description": "C runtime entry point",+ "indicators": {+ "constants": [],+ "patterns": [+ "calls main with argc/argv/envp, sets up atexit"+ ],+ "strings": []+ },+ "signature": "int __libc_start_main(int (*main)(int, char **, char **), int argc, char **argv, void (*init)(void), void (*fini)(void), void (*rtld_fini)(void), void *stack_end)"+ },+ {+ "name": "_start",+ "aliases": [+ "_entry"+ ],+ "description": "ELF entry point",+ "indicators": {+ "constants": [],+ "patterns": [+ "first function, sets up stack alignment, calls __libc_start_main"+ ],+ "strings": []+ },+ "signature": "void _start(void)"+ },+ {+ "name": "__cxa_atexit",+ "aliases": [],+ "description": "Register destructor for C++ static object",+ "indicators": {+ "constants": [],+ "patterns": [+ "registers function pointer for cleanup at exit"+ ],+ "strings": []+ },+ "signature": "int __cxa_atexit(void (*func)(void *), void *arg, void *dso_handle)"+ },+ {+ "name": "getenv",+ "aliases": [+ "__getenv"+ ],+ "description": "Get environment variable",+ "indicators": {+ "constants": [],+ "patterns": [+ "scan environ array for name=value match"+ ],+ "strings": []+ },+ "signature": "char *getenv(const char *name)"+ },+ {+ "name": "open",+ "aliases": [+ "open64",+ "__open"+ ],+ "description": "Open file descriptor",+ "indicators": {+ "constants": [],+ "patterns": [+ "syscall open with path, flags, optional mode"+ ],+ "strings": []+ },+ "signature": "int open(const char *pathname, int flags, ...)"+ },+ {+ "name": "close",+ "aliases": [+ "__close"+ ],+ "description": "Close file descriptor",+ "indicators": {+ "constants": [],+ "patterns": [+ "syscall close on fd"+ ],+ "strings": []+ },+ "signature": "int close(int fd)"+ },+ {+ "name": "read",+ "aliases": [+ "__read"+ ],+ "description": "Read from file descriptor",+ "indicators": {+ "constants": [],+ "patterns": [+ "syscall read: fd, buffer, count"+ ],+ "strings": []+ },+ "signature": "ssize_t read(int fd, void *buf, size_t count)"+ },+ {+ "name": "write",+ "aliases": [+ "__write"+ ],+ "description": "Write to file descriptor",+ "indicators": {+ "constants": [],+ "patterns": [+ "syscall write: fd, buffer, count"+ ],+ "strings": []+ },+ "signature": "ssize_t write(int fd, const void *buf, size_t count)"+ },+ {+ "name": "mmap",+ "aliases": [+ "mmap64",+ "__mmap"+ ],+ "description": "Map memory",+ "indicators": {+ "constants": [],+ "patterns": [+ "syscall mmap with addr, length, prot, flags, fd, offset"+ ],+ "strings": []+ },+ "signature": "void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset)"+ },+ {+ "name": "munmap",+ "aliases": [+ "__munmap"+ ],+ "description": "Unmap memory",+ "indicators": {+ "constants": [],+ "patterns": [+ "syscall munmap with addr, length"+ ],+ "strings": []+ },+ "signature": "int munmap(void *addr, size_t length)"+ }+]