The world's first agentic reverse engineer.
deobfuscator p1
Amruth045e8e62579b
diff --git a/kong/agent/analyzer.py b/kong/agent/analyzer.pyindex d33df71..5d9311b 100644--- a/kong/agent/analyzer.py+++ b/kong/agent/analyzer.py@@ -21,13 +21,19 @@ logger = logging.getLogger(__name__)class LLMClient(Protocol):- """Protocol for LLM interaction.-- TODO: add concrete implementation that uses Anthropic SDK.- """+ """Protocol for LLM interaction."""def analyze_function(self, prompt: str) -> LLMResponse: ...+ def analyze_with_tools(+ self,+ prompt: str,+ system: str,+ tools: list[dict[str, object]],+ tool_executor: object,+ max_rounds: int = 10,+ ) -> LLMResponse: ...+@dataclassclass LLMResponse:@@ -99,7 +105,8 @@ class CalleeSnippet:class Analyzer:"""Analyzes a single function: gather context → LLM → parse → write back.- Usage:+ Usage::+analyzer = Analyzer(ghidra_client, llm_client)result = analyzer.analyze(work_item, binary_info, known_results, strings)"""@@ -108,9 +115,11 @@ class Analyzer:self,client: GhidraClient,llm_client: LLMClient,+ deobfuscator: object | None = None,) -> None:self.client = clientself.llm = llm_client+ self._deobfuscator = deobfuscatordef analyze(self,@@ -121,14 +130,35 @@ class Analyzer:known_types: list[StructDefinition] | None = None,) -> FunctionResult:"""Full analysis pipeline for one function."""- func = item.function+ from kong.agent.deobfuscator import Deobfuscator, classify_obfuscation+ func = item.functioncontext = self._build_context(item, binary_info, known_results, strings, known_types)- prompt = self._build_prompt(context)- response = self.llm.analyze_function(prompt)+ techniques = classify_obfuscation(context.decompilation) if self._deobfuscator else []++ if techniques and isinstance(self._deobfuscator, Deobfuscator):+ response, tool_calls = self._deobfuscator.deobfuscate(context, techniques)+ sig_applied = 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,+ signature_applied=sig_applied,+ struct_proposals=response.struct_proposals,+ obfuscation_techniques=[t.value for t in techniques],+ deobfuscation_tool_calls=tool_calls,+ )- self._write_back(func.address, response)+ prompt = self._build_prompt(context)+ response = self.llm.analyze_function(prompt)+ sig_applied = self._write_back(func.address, response)return FunctionResult(address=func.address,@@ -140,6 +170,7 @@ class Analyzer:comments=response.comments,reasoning=response.reasoning,llm_calls=1,+ signature_applied=sig_applied,struct_proposals=response.struct_proposals,)@@ -314,19 +345,26 @@ class Analyzer:return "\n".join(parts)- def _write_back(self, addr: int, response: LLMResponse) -> None:- """Write analysis results back to Ghidra."""+ def _write_back(self, addr: int, response: LLMResponse) -> bool:+ """Write analysis results back to Ghidra.++ Returns True if the signature was successfully applied (or no+ signature was provided), False if it failed (typically because the+ signature references a type that doesn't exist yet).+ """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)+ signature_ok = Trueif 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)+ signature_ok = Falseif response.comments:try:@@ -334,6 +372,8 @@ class Analyzer:except Exception as e:logger.warning("Failed to add comment at 0x%08x: %s", addr, e)+ return signature_ok+@staticmethoddef parse_llm_json(raw: str) -> LLMResponse:"""Parse the LLM's JSON response into an LLMResponse.diff --git a/kong/agent/deobfuscator.py b/kong/agent/deobfuscator.pynew file mode 100644index 0000000..3438857--- /dev/null+++ b/kong/agent/deobfuscator.py@@ -0,0 +1,263 @@+"""Deobfuscator agent — classifies obfuscation techniques and orchestrates+LLM-driven deobfuscation with symbolic tool access.+"""++from __future__ import annotations++import logging+import re+from enum import Enum+from pathlib import Path+from typing import TYPE_CHECKING++from kong.agent.analyzer import AnalysisContext, LLMClient, LLMResponse+from kong.agent.models import FunctionResult+from kong.agent.prompts import DEOBFUSCATION_SYSTEM_PROMPT, OUTPUT_SCHEMA+from kong.ghidra.types import BinaryInfo, StringEntry+from kong.llm.tools import DEOBFUSCATION_TOOLS, ToolExecutor++if TYPE_CHECKING:+ from kong.agent.queue import WorkItem+ from kong.ghidra.client import GhidraClient++logger = logging.getLogger(__name__)++_PATTERNS_DIR = Path(__file__).resolve().parent.parent / "patterns"+++class ObfuscationType(Enum):+ CONTROL_FLOW_FLATTENING = "cff"+ BOGUS_CONTROL_FLOW = "bogus_cf"+ INSTRUCTION_SUBSTITUTION = "instruction_sub"+ STRING_ENCRYPTION = "string_encrypt"+ VM_PROTECTION = "vmprotect"+++_PATTERN_FILES: dict[ObfuscationType, str] = {+ ObfuscationType.CONTROL_FLOW_FLATTENING: "cff.md",+ ObfuscationType.BOGUS_CONTROL_FLOW: "bogus_cf.md",+ ObfuscationType.INSTRUCTION_SUBSTITUTION: "instruction_sub.md",+ ObfuscationType.STRING_ENCRYPTION: "string_encrypt.md",+ ObfuscationType.VM_PROTECTION: "vmprotect.md",+}+++# -----------------------------------------------------------------------+# Classification heuristics+# -----------------------------------------------------------------------++_CFF_LOOP_RE = re.compile(+ r"while\s*\(\s*(?:1|true)\s*\)\s*\{",+ re.IGNORECASE,+)+_SWITCH_RE = re.compile(r"switch\s*\(")+_CASE_RE = re.compile(r"case\s+(?:0x[0-9a-fA-F]+|\d+)\s*:")++_OPAQUE_PATTERNS: list[re.Pattern[str]] = [+ re.compile(r"\(\s*\w+\s*\*\s*\(\s*\w+\s*[+\-]\s*\d+\s*\)\s*\)\s*%\s*2"),+ re.compile(r"\w+\s*\^\s*\w+\s*\)\s*!=\s*0"),+ re.compile(r"\w+\s*&\s*~\s*\w+"),+ re.compile(r"\w+\s*\|\s*~\s*\w+"),+]++_INSTRUCTION_SUB_PATTERNS: list[re.Pattern[str]] = [+ re.compile(r"\(\s*~\s*\w+\s*&\s*\w+\s*\)\s*\|\s*\(\s*\w+\s*&\s*~\s*\w+\s*\)"),+ re.compile(r"\(\s*\w+\s*\^\s*\w+\s*\)\s*\+\s*2\s*\*\s*\(\s*\w+\s*&\s*\w+\s*\)"),+ re.compile(r"~\s*\w+\s*\+\s*1"),+]++_STRING_ENCRYPT_XOR_RE = re.compile(+ r"for\s*\([^)]*\)\s*\{[^}]*\^\s*=\s*(?:0x[0-9a-fA-F]+|\d+)\s*;",+ re.DOTALL,+)+_STACK_STRING_RE = re.compile(+ r"(?:\w+\[\d+\]\s*=\s*(?:0x[0-9a-fA-F]{2}|'\\.?')\s*;\s*){4,}"+)+++def classify_obfuscation(decompiled: str) -> list[ObfuscationType]:+ """Heuristic classification of obfuscation techniques in decompiled code."""+ techniques: list[ObfuscationType] = []++ if _detect_cff(decompiled):+ techniques.append(ObfuscationType.CONTROL_FLOW_FLATTENING)++ if _detect_bogus_cf(decompiled):+ techniques.append(ObfuscationType.BOGUS_CONTROL_FLOW)++ if _detect_instruction_sub(decompiled):+ techniques.append(ObfuscationType.INSTRUCTION_SUBSTITUTION)++ if _detect_string_encrypt(decompiled):+ techniques.append(ObfuscationType.STRING_ENCRYPTION)++ if _detect_vmprotect(decompiled):+ techniques.append(ObfuscationType.VM_PROTECTION)++ return techniques+++def _detect_cff(code: str) -> bool:+ """while(1)/switch with many hex-constant cases and a state variable."""+ if not _CFF_LOOP_RE.search(code):+ return False+ if not _SWITCH_RE.search(code):+ return False+ cases = _CASE_RE.findall(code)+ return len(cases) >= 4+++def _detect_bogus_cf(code: str) -> bool:+ match_count = sum(1 for p in _OPAQUE_PATTERNS if p.search(code))+ return match_count >= 2+++def _detect_instruction_sub(code: str) -> bool:+ match_count = sum(1 for p in _INSTRUCTION_SUB_PATTERNS if p.search(code))+ return match_count >= 2+++def _detect_string_encrypt(code: str) -> bool:+ if _STRING_ENCRYPT_XOR_RE.search(code):+ return True+ return bool(_STACK_STRING_RE.search(code))+++def _detect_vmprotect(code: str) -> bool:+ if not _CFF_LOOP_RE.search(code):+ return False+ if not _SWITCH_RE.search(code):+ return False+ cases = _CASE_RE.findall(code)+ if len(cases) < 15:+ return False+ lines = code.splitlines()+ return len(lines) > 200+++# -----------------------------------------------------------------------+# Pattern library loader+# -----------------------------------------------------------------------++def load_patterns(techniques: list[ObfuscationType]) -> str:+ """Load and concatenate pattern library files for the given techniques."""+ parts: list[str] = []+ for tech in techniques:+ filename = _PATTERN_FILES.get(tech)+ if filename is None:+ continue+ path = _PATTERNS_DIR / filename+ if path.exists():+ parts.append(path.read_text(encoding="utf-8"))+ else:+ logger.warning("Pattern file not found: %s", path)+ return "\n\n---\n\n".join(parts)+++# -----------------------------------------------------------------------+# Deobfuscator+# -----------------------------------------------------------------------++class Deobfuscator:+ """Orchestrates LLM-driven deobfuscation with symbolic tool access.++ Usage::++ deobfuscator = Deobfuscator(ghidra_client, llm_client)+ techniques = classify_obfuscation(decompilation)+ if techniques:+ result = deobfuscator.deobfuscate(item, binary_info, ...)+ """++ def __init__(+ self,+ client: GhidraClient,+ llm_client: LLMClient,+ ) -> None:+ self.client = client+ self.llm = llm_client++ def deobfuscate(+ self,+ context: AnalysisContext,+ techniques: list[ObfuscationType],+ ) -> tuple[LLMResponse, int]:+ """Run LLM-driven deobfuscation with tool access.++ Returns (LLMResponse, tool_call_count).+ """+ pattern_context = load_patterns(techniques)+ prompt = self._build_prompt(context, techniques, pattern_context)+ executor = ToolExecutor(self.client)++ response = self.llm.analyze_with_tools(+ prompt=prompt,+ system=DEOBFUSCATION_SYSTEM_PROMPT,+ tools=DEOBFUSCATION_TOOLS,+ tool_executor=executor,+ )+ return response, executor.call_count++ def _build_prompt(+ self,+ context: AnalysisContext,+ techniques: list[ObfuscationType],+ pattern_context: str,+ ) -> str:+ parts: list[str] = []++ parts.append(+ f"Binary: {context.binary_info.arch} {context.binary_info.format} "+ f"({context.binary_info.compiler})"+ )+ parts.append("")++ tech_names = ", ".join(t.value for t in techniques)+ parts.append(f"## Obfuscation Detected: {tech_names}")+ 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}")++ if pattern_context:+ parts.append("")+ parts.append("### Obfuscation Pattern Reference")+ parts.append(pattern_context)++ return "\n".join(parts)diff --git a/kong/agent/events.py b/kong/agent/events.pyindex 36fddb4..e5d0e03 100644--- a/kong/agent/events.py+++ b/kong/agent/events.py@@ -33,6 +33,11 @@ class EventType(Enum):CLEANUP_TYPES_UNIFIED = "cleanup_types_unified"CLEANUP_TYPE_CREATED = "cleanup_type_created"+ CLEANUP_SIGNATURES_RETRIED = "cleanup_signatures_retried"++ DEOBFUSCATION_DETECTED = "deobfuscation_detected"+ DEOBFUSCATION_TOOL_CALL = "deobfuscation_tool_call"+ DEOBFUSCATION_COMPLETE = "deobfuscation_complete"EXPORT_FILE = "export_file"diff --git a/kong/agent/models.py b/kong/agent/models.pyindex 15a4280..9f5d3df 100644--- a/kong/agent/models.py+++ b/kong/agent/models.py@@ -24,4 +24,7 @@ class FunctionResult:llm_calls: int = 0skipped: bool = Falseskip_reason: str = ""+ signature_applied: bool = Falsestruct_proposals: list[StructProposal] = field(default_factory=list)+ obfuscation_techniques: list[str] = field(default_factory=list)+ deobfuscation_tool_calls: int = 0diff --git a/kong/agent/prompts.py b/kong/agent/prompts.pyindex a81cd8c..8a06fe4 100644--- a/kong/agent/prompts.py+++ b/kong/agent/prompts.py@@ -21,6 +21,35 @@ concrete offsets — do not propose structs for single-field or ambiguous accessYou respond only with a JSON object. No prose before or after."""++DEOBFUSCATION_SYSTEM_PROMPT = """\+You are an expert reverse engineer specializing in deobfuscation of stripped \+binaries. You are given obfuscated decompiled C code from Ghidra along with \+pattern references describing the obfuscation techniques detected.++You have access to symbolic analysis tools. Use them to:+1. Simplify suspicious expressions and detect opaque predicates+2. Trace control-flow-flattening state machines+3. Eliminate dead code after resolving predicates+4. Identify cryptographic constants+5. Re-fetch decompilation or basic blocks as needed++Your workflow for obfuscated functions:+1. Read the decompilation and the pattern reference carefully+2. Identify specific obfuscation artifacts (opaque predicates, state variables, \+substituted expressions)+3. Use the appropriate tools to resolve each artifact+4. Reason about the cleaned control flow to determine the function's real purpose+5. Return your analysis as JSON++Your analysis must be precise:+- Name functions based on the recovered (deobfuscated) logic+- Use standard naming conventions (snake_case for C, camelCase for C++)+- If the function is too heavily obfuscated to recover, say so honestly+- Confidence should reflect how certain you are of the recovery, not just the naming++You MUST respond with a JSON object as your final answer. No prose before or after."""+OUTPUT_SCHEMA = """\Respond with exactly one JSON object:```jsondiff --git a/kong/agent/supervisor.py b/kong/agent/supervisor.pyindex 6c36e67..6fbd4bd 100644--- a/kong/agent/supervisor.py+++ b/kong/agent/supervisor.py@@ -6,10 +6,12 @@ Emits structured events for TUI/CLI consumption.from __future__ import annotations+import loggingimport timefrom dataclasses import dataclassfrom kong.agent.analyzer import Analyzer, LLMClient+from kong.agent.deobfuscator import Deobfuscatorfrom kong.agent.events import Event, EventCallback, EventType, Phasefrom kong.agent.models import FunctionResultfrom kong.agent.queue import WorkItem, WorkQueue@@ -20,6 +22,8 @@ from kong.config import KongConfigfrom kong.ghidra.client import GhidraClientfrom kong.ghidra.types import BinaryInfo, FunctionInfo, StringEntry+logger = logging.getLogger(__name__)+@dataclassclass AnalysisStats:@@ -312,14 +316,32 @@ class Supervisor:confidence=0,)- analyzer = Analyzer(self.client, self.llm_client)- return analyzer.analyze(+ deobfuscator = Deobfuscator(self.client, self.llm_client)+ analyzer = Analyzer(self.client, self.llm_client, deobfuscator=deobfuscator)+ result = analyzer.analyze(item,binary_info=self.binary_info,known_results=self.results,strings=self.strings,)+ if result.obfuscation_techniques:+ self._emit(Event(+ type=EventType.DEOBFUSCATION_DETECTED,+ phase=Phase.ANALYSIS,+ message=(+ f"Obfuscation detected in {func.name}: "+ f"{', '.join(result.obfuscation_techniques)}"+ ),+ data={+ "address": func.address,+ "techniques": result.obfuscation_techniques,+ "tool_calls": result.deobfuscation_tool_calls,+ },+ ))++ return result+def _run_cleanup(self) -> None:"""Unify struct types, apply to Ghidra, re-analyze affected and low-confidence functions."""self._emit(Event(@@ -364,6 +386,35 @@ class Supervisor:},))+ pending_signatures = [+ r for r in self.results.values()+ if r.signature and not r.signature_applied and not r.skipped and not r.error+ ]+ if pending_signatures:+ sigs_retried = 0+ for r in pending_signatures:+ try:+ self.client.set_function_signature(r.address, r.signature)+ r.signature_applied = True+ sigs_retried += 1+ except Exception:+ logger.debug(+ "Signature retry still failed for 0x%08x: %s",+ r.address, r.signature,+ )+ self._emit(Event(+ type=EventType.CLEANUP_SIGNATURES_RETRIED,+ phase=Phase.CLEANUP,+ message=(+ f"Retried {len(pending_signatures)} pending signatures, "+ f"{sigs_retried} succeeded."+ ),+ data={+ "pending": len(pending_signatures),+ "succeeded": sigs_retried,+ },+ ))+low_confidence = [r for r in self.results.values()if not r.skipped and not r.error and r.confidence < 50diff --git a/kong/agent/type_recovery.py b/kong/agent/type_recovery.pyindex 142bb2b..1d21f6d 100644--- a/kong/agent/type_recovery.py+++ b/kong/agent/type_recovery.py@@ -81,14 +81,13 @@ class StructAccumulator:return [self._merge_group(g) for g in groups]def _group_proposals(self) -> list[list[StructProposal]]:- by_size: dict[int, list[StructProposal]] = defaultdict(list)+ by_name: dict[str, list[StructProposal]] = defaultdict(list)for p in self._proposals:- by_size[p.total_size].append(p)+ by_name[p.name].append(p)groups: list[list[StructProposal]] = []- for same_size in by_size.values():- sub = self._split_by_field_overlap(same_size)- groups.extend(sub)+ for same_name in by_name.values():+ groups.append(same_name)return groups@staticmethod@@ -148,7 +147,12 @@ class StructAccumulator:size=best.size,))- total_size = group[0].total_size+ max_size = max(p.total_size for p in group)+ last_field_end = max(+ (f.offset + f.size for f in merged_fields),+ default=0,+ )+ total_size = max(max_size, last_field_end)definition = StructDefinition(name=winning_name,size=total_size,diff --git a/kong/ghidra/client.py b/kong/ghidra/client.pyindex c1b8c5b..0f2e007 100644--- a/kong/ghidra/client.py+++ b/kong/ghidra/client.py@@ -13,11 +13,18 @@ from typing import Anyimport pyghidrafrom kong.ghidra.types import (+ BasicBlock,BinaryInfo,+ BlockEdge,+ BlockEdgeType,+ ControlFlowGraph,FunctionClassification,FunctionInfo,ParameterInfo,+ PcodeOp,StringEntry,+ StructDefinition,+ StructField,VariableInfo,XRef,)@@ -344,6 +351,340 @@ class GhidraClient:self.program.endTransaction(tx, True)logger.info("Added %s comment at 0x%08x", comment_type, addr)+ # ------------------------------------------------------------------+ # Type management methods+ # ------------------------------------------------------------------++ def create_struct(self, definition: StructDefinition) -> None:+ """Create a struct data type in Ghidra's DataTypeManager.++ Fields are placed at explicit offsets within the struct. Gaps between+ fields are left as undefined bytes (Ghidra fills them automatically).+ """+ from ghidra.program.model.data import (+ CategoryPath,+ StructureDataType,+ )++ dtm = self.program.getDataTypeManager()+ category = CategoryPath("/kong")++ struct_dt = StructureDataType(category, definition.name, definition.size)+ for fld in definition.fields:+ ghidra_type = self._resolve_data_type(fld.data_type, fld.size)+ struct_dt.replaceAtOffset(fld.offset, ghidra_type, fld.size, fld.name, None)++ tx = self.program.startTransaction("create_struct")+ try:+ dtm.addDataType(struct_dt, None)+ finally:+ self.program.endTransaction(tx, True)+ logger.info("Created struct '%s' (%d bytes, %d fields)", definition.name, definition.size, definition.field_count)++ def apply_type_to_param(+ self,+ func_addr: int,+ param_ordinal: int,+ type_name: str,+ as_pointer: bool = True,+ ) -> None:+ """Apply a data type (optionally as a pointer) to a function parameter."""+ from ghidra.program.model.data import PointerDataType+ from ghidra.program.model.symbol import SourceType++ func = self._get_function_at(func_addr)+ params = func.getParameters()+ if param_ordinal >= len(params):+ raise GhidraClientError(+ f"Parameter ordinal {param_ordinal} out of range for "+ f"function at 0x{func_addr:08x} ({len(params)} params)"+ )++ resolved = self._lookup_type(type_name)+ if resolved is None:+ raise GhidraClientError(f"Type '{type_name}' not found in DataTypeManager")++ target_type = PointerDataType(resolved) if as_pointer else resolved++ tx = self.program.startTransaction("apply_type_to_param")+ try:+ param = params[param_ordinal]+ param.setDataType(target_type, SourceType.USER_DEFINED)+ finally:+ self.program.endTransaction(tx, True)+ logger.info(+ "Applied type '%s%s' to param %d of function at 0x%08x",+ type_name, " *" if as_pointer else "", param_ordinal, func_addr,+ )++ def list_custom_types(self) -> list[StructDefinition]:+ """List all struct types in the /kong category."""+ from ghidra.program.model.data import CategoryPath, Structure++ dtm = self.program.getDataTypeManager()+ category = dtm.getCategory(CategoryPath("/kong"))+ if category is None:+ return []++ results: list[StructDefinition] = []+ for dt in category.getDataTypes():+ if not isinstance(dt, Structure):+ continue+ fields = []+ for i in range(dt.getNumDefinedComponents()):+ comp = dt.getComponent(i)+ fields.append(StructField(+ name=str(comp.getFieldName() or f"field_{i}"),+ data_type=str(comp.getDataType().getDisplayName()),+ offset=int(comp.getOffset()),+ size=int(comp.getLength()),+ ))+ results.append(StructDefinition(+ name=str(dt.getName()),+ size=int(dt.getLength()),+ fields=fields,+ ))+ return results++ def get_type(self, name: str) -> StructDefinition | None:+ """Look up a struct type by name from the /kong category."""+ from ghidra.program.model.data import Structure++ resolved = self._lookup_type(name)+ if resolved is None or not isinstance(resolved, Structure):+ return None++ fields = []+ for i in range(resolved.getNumDefinedComponents()):+ comp = resolved.getComponent(i)+ fields.append(StructField(+ name=str(comp.getFieldName() or f"field_{i}"),+ data_type=str(comp.getDataType().getDisplayName()),+ offset=int(comp.getOffset()),+ size=int(comp.getLength()),+ ))+ return StructDefinition(+ name=str(resolved.getName()),+ size=int(resolved.getLength()),+ fields=fields,+ )++ def _lookup_type(self, name: str) -> Any:+ """Search for a data type by name, checking /kong category first."""+ from ghidra.program.model.data import CategoryPath+ from java.util import ArrayList++ dtm = self.program.getDataTypeManager()+ category = dtm.getCategory(CategoryPath("/kong"))+ if category is not None:+ for dt in category.getDataTypes():+ if str(dt.getName()) == name:+ return dt++ results = ArrayList()+ dtm.findDataTypes(name, results)+ return results.get(0) if results.size() > 0 else None++ def _resolve_data_type(self, type_name: str, size: int) -> Any:+ """Resolve a C type name to a Ghidra DataType, falling back to sized defaults."""+ from ghidra.program.model.data import (+ ByteDataType,+ CharDataType,+ IntegerDataType,+ LongDataType,+ LongLongDataType,+ PointerDataType,+ ShortDataType,+ UnsignedIntegerDataType,+ UnsignedLongDataType,+ UnsignedLongLongDataType,+ UnsignedShortDataType,+ Undefined1DataType,+ Undefined2DataType,+ Undefined4DataType,+ Undefined8DataType,+ )++ _BUILTIN: dict[str, Any] = {+ "byte": ByteDataType.dataType,+ "char": CharDataType.dataType,+ "short": ShortDataType.dataType,+ "int": IntegerDataType.dataType,+ "long": LongDataType.dataType,+ "long long": LongLongDataType.dataType,+ "uint8_t": ByteDataType.dataType,+ "uint16_t": UnsignedShortDataType.dataType,+ "uint32_t": UnsignedIntegerDataType.dataType,+ "uint64_t": UnsignedLongLongDataType.dataType,+ "int8_t": CharDataType.dataType,+ "int16_t": ShortDataType.dataType,+ "int32_t": IntegerDataType.dataType,+ "int64_t": LongLongDataType.dataType,+ "unsigned int": UnsignedIntegerDataType.dataType,+ "unsigned long": UnsignedLongDataType.dataType,+ "unsigned short": UnsignedShortDataType.dataType,+ }++ if type_name.endswith("*"):+ base_name = type_name.rstrip("* ").strip()+ base_type = self._resolve_data_type(base_name, self.program.getDefaultPointerSize())+ return PointerDataType(base_type)++ low = type_name.lower().strip()+ if low in _BUILTIN:+ return _BUILTIN[low]++ found = self._lookup_type(type_name)+ if found is not None:+ return found++ _SIZED_DEFAULTS: dict[int, Any] = {+ 1: Undefined1DataType.dataType,+ 2: Undefined2DataType.dataType,+ 4: Undefined4DataType.dataType,+ 8: Undefined8DataType.dataType,+ }+ return _SIZED_DEFAULTS.get(size, Undefined4DataType.dataType)++ # ------------------------------------------------------------------+ # Control flow graph methods+ # ------------------------------------------------------------------++ def get_basic_blocks(self, addr: int) -> list[BasicBlock]:+ """Get basic blocks for the function at addr."""+ from ghidra.program.model.block import SimpleBlockModel+ from ghidra.util.task import ConsoleTaskMonitor++ func = self._get_function_at(addr)+ body = func.getBody()+ model = SimpleBlockModel(self.program)+ monitor = ConsoleTaskMonitor()++ blocks: list[BasicBlock] = []+ block_iter = model.getCodeBlocksContaining(body, monitor)+ while block_iter.hasNext():+ block = block_iter.next()+ start = int(block.getFirstStartAddress().getOffset())+ end = int(block.getMaxAddress().getOffset())+ instructions = self._disassemble_range(start, end)+ blocks.append(BasicBlock(+ start_addr=start,+ end_addr=end,+ instructions=instructions,+ ))+ return blocks++ def get_control_flow_graph(self, addr: int) -> ControlFlowGraph:+ """Build a complete control flow graph for the function at addr."""+ from ghidra.program.model.block import SimpleBlockModel+ from ghidra.util.task import ConsoleTaskMonitor++ func = self._get_function_at(addr)+ body = func.getBody()+ model = SimpleBlockModel(self.program)+ monitor = ConsoleTaskMonitor()++ blocks: list[BasicBlock] = []+ edges: list[BlockEdge] = []+ block_iter = model.getCodeBlocksContaining(body, monitor)+ while block_iter.hasNext():+ block = block_iter.next()+ start = int(block.getFirstStartAddress().getOffset())+ end = int(block.getMaxAddress().getOffset())+ instructions = self._disassemble_range(start, end)+ blocks.append(BasicBlock(+ start_addr=start,+ end_addr=end,+ instructions=instructions,+ ))++ dest_iter = block.getDestinations(monitor)+ while dest_iter.hasNext():+ dest_ref = dest_iter.next()+ dest_block = dest_ref.getDestinationBlock()+ if dest_block is None:+ continue+ dest_addr = int(dest_block.getFirstStartAddress().getOffset())+ if not body.contains(dest_block.getFirstStartAddress()):+ continue+ flow_type = dest_ref.getFlowType()+ edge_type = self._classify_flow(flow_type)+ edges.append(BlockEdge(+ from_addr=start,+ to_addr=dest_addr,+ edge_type=edge_type,+ ))++ return ControlFlowGraph(+ function_addr=int(func.getEntryPoint().getOffset()),+ blocks=blocks,+ edges=edges,+ )++ def get_pcode_ops(self, addr: int) -> list[PcodeOp]:+ """Get high-level pcode operations for the function at addr."""+ from ghidra.app.decompiler import DecompInterface+ from ghidra.util.task import ConsoleTaskMonitor++ func = self._get_function_at(addr)+ di = DecompInterface()+ try:+ di.openProgram(self.program)+ result = di.decompileFunction(func, 30, ConsoleTaskMonitor())+ if not result.decompileCompleted():+ raise GhidraClientError(+ f"Decompilation failed for pcode at 0x{addr:08x}"+ )+ high_func = result.getHighFunction()+ if high_func is None:+ return []++ ops: list[PcodeOp] = []+ op_iter = high_func.getPcodeOps()+ while op_iter.hasNext():+ op = op_iter.next()+ mnemonic = str(op.getMnemonic())+ op_addr = int(op.getSeqnum().getTarget().getOffset())+ inputs = [+ str(op.getInput(i)) for i in range(op.getNumInputs())+ ]+ output = str(op.getOutput()) if op.getOutput() is not None else ""+ ops.append(PcodeOp(+ mnemonic=mnemonic,+ address=op_addr,+ inputs=inputs,+ output=output,+ ))+ return ops+ finally:+ di.dispose()++ def _disassemble_range(self, start: int, end: int) -> list[str]:+ """Get disassembly text for instructions in an address range."""+ listing = self.program.getListing()+ start_addr = self._to_addr(start)+ end_addr = self._to_addr(end)+ instructions: list[str] = []+ instr = listing.getInstructionAt(start_addr)+ while instr is not None and instr.getAddress().compareTo(end_addr) <= 0:+ instructions.append(str(instr))+ instr = instr.getNext()+ return instructions++ @staticmethod+ def _classify_flow(flow_type: object) -> BlockEdgeType:+ """Map a Ghidra FlowType to our BlockEdgeType enum."""+ name = str(flow_type)+ if "FALL_THROUGH" in name:+ return BlockEdgeType.FALL_THROUGH+ if "UNCONDITIONAL_JUMP" in name or "CONDITIONAL_JUMP" in name:+ return BlockEdgeType.BRANCH+ if "CALL" in name:+ return BlockEdgeType.CALL+ if "COMPUTED" in name or "INDIRECT" in name:+ return BlockEdgeType.COMPUTED+ return BlockEdgeType.UNKNOWN+# ------------------------------------------------------------------# Helpers# ------------------------------------------------------------------diff --git a/kong/ghidra/types.py b/kong/ghidra/types.pyindex 6c26254..01bbd27 100644--- a/kong/ghidra/types.py+++ b/kong/ghidra/types.py@@ -86,3 +86,98 @@ class BinaryInfo:path: str = ""min_address: int = 0max_address: int = 0+++@dataclass+class StructField:+ name: str+ data_type: str+ offset: int+ size: int++ @property+ def end_offset(self) -> int:+ return self.offset + self.size+++@dataclass+class StructDefinition:+ name: str+ size: int+ fields: list[StructField] = field(default_factory=list)++ @property+ def field_count(self) -> int:+ return len(self.fields)++ def field_at_offset(self, offset: int) -> StructField | None:+ for f in self.fields:+ if f.offset == offset:+ return f+ return None+++@dataclass+class PcodeOp:+ """A single pcode operation within a basic block."""+ mnemonic: str+ address: int+ inputs: list[str] = field(default_factory=list)+ output: str = ""+++@dataclass+class BasicBlock:+ """A basic block within a function's control flow graph."""+ start_addr: int+ end_addr: int+ instructions: list[str] = field(default_factory=list)+ pcode_ops: list[PcodeOp] = field(default_factory=list)++ @property+ def start_hex(self) -> str:+ return f"0x{self.start_addr:08x}"++ @property+ def end_hex(self) -> str:+ return f"0x{self.end_addr:08x}"+++class BlockEdgeType(Enum):+ FALL_THROUGH = "fall_through"+ BRANCH = "branch"+ CALL = "call"+ COMPUTED = "computed"+ UNKNOWN = "unknown"+++@dataclass+class BlockEdge:+ """A directed edge in the control flow graph."""+ from_addr: int+ to_addr: int+ edge_type: BlockEdgeType = BlockEdgeType.UNKNOWN+++@dataclass+class ControlFlowGraph:+ """Control flow graph for a single function."""+ function_addr: int+ blocks: list[BasicBlock] = field(default_factory=list)+ edges: list[BlockEdge] = field(default_factory=list)++ @property+ def block_count(self) -> int:+ return len(self.blocks)++ def block_at(self, addr: int) -> BasicBlock | None:+ for b in self.blocks:+ if b.start_addr == addr:+ return b+ return None++ def successors(self, addr: int) -> list[int]:+ return [e.to_addr for e in self.edges if e.from_addr == addr]++ def predecessors(self, addr: int) -> list[int]:+ return [e.from_addr for e in self.edges if e.to_addr == addr]