fix(ghidra): recover returning import callers
This commit is contained in:
@@ -14,6 +14,15 @@ binaries and Ghidra projects are never committed.
|
||||
x86-64 PE, and x86-64 Mach-O targets from the same semantics. It preserves an
|
||||
exported entry, direct and indirect calls, a volatile string reference, and a
|
||||
multi-block branch across loaders.
|
||||
- `no-return.c` and `ReaNoReturnProbe.java` inject incorrect import flags into a
|
||||
real ELF analysis database, verify caller recovery, propagated flag repair and signature preservation,
|
||||
and retain genuine/unknown no-return calls and independently identified entries.
|
||||
Run `npm run build:cached`, then `node scripts/verify-real-ghidra-noreturn.mjs`
|
||||
with the Ghidra/JDK environment below on Linux x64 and a procps-compatible process
|
||||
table that exposes REA's current process for owned cleanup. It also checks named
|
||||
limitations through the real read-only TCP bridge and provider Evidence
|
||||
projection; default Unix-socket transport, Windows, and the reported Amethyst
|
||||
artifact need separate verification. Fixture target code is never executed.
|
||||
|
||||
`scripts/verify-real-ghidra.mjs` uses `cc`, `clang`, and `lld-link` by default;
|
||||
`REA_CC`, `REA_CLANG`, and `REA_LLD_LINK` can select alternate commands. The
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
//@category REA Verification
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import generic.jar.ResourceFile;
|
||||
import ghidra.app.script.GhidraScript;
|
||||
import ghidra.app.script.GhidraScriptUtil;
|
||||
import ghidra.framework.Application;
|
||||
import ghidra.program.model.address.Address;
|
||||
import ghidra.program.model.address.AddressSet;
|
||||
import ghidra.program.model.listing.FlowOverride;
|
||||
import ghidra.program.model.listing.Function;
|
||||
import ghidra.program.model.listing.Instruction;
|
||||
import ghidra.program.model.symbol.SourceType;
|
||||
import java.io.File;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.file.Files;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Injects the reported analysis flags into real imported ELF functions; never executes ELF code. */
|
||||
public class ReaNoReturnProbe extends GhidraScript {
|
||||
private final JsonArray checks = new JsonArray();
|
||||
private final Map<Function, Address> originalEnds = new LinkedHashMap<>();
|
||||
private final Map<Function, String> originalSignatures = new LinkedHashMap<>();
|
||||
|
||||
private void require(String name, boolean condition) {
|
||||
if (!condition) throw new IllegalStateException("No-return assertion failed: " + name);
|
||||
checks.add(name);
|
||||
}
|
||||
|
||||
private Function function(String name) {
|
||||
for (Function f : currentProgram.getFunctionManager().getFunctions(true))
|
||||
if (!f.isThunk() && f.getName().equals(name)) return f;
|
||||
throw new IllegalStateException("Missing fixture function " + name);
|
||||
}
|
||||
|
||||
private Function external(String name) {
|
||||
for (Function f : currentProgram.getFunctionManager().getExternalFunctions())
|
||||
if (f.getName().equals(name)) return f;
|
||||
throw new IllegalStateException("Missing imported function " + name);
|
||||
}
|
||||
|
||||
private void truncate(Function caller, String callee) throws Exception {
|
||||
truncate(caller, external(callee));
|
||||
}
|
||||
|
||||
private void truncate(Function caller, Function callee) throws Exception {
|
||||
for (Instruction ins : currentProgram.getListing().getInstructions(caller.getBody(), true)) {
|
||||
if (!ins.getFlowType().isCall()) continue;
|
||||
Address[] flows = ins.getFlows();
|
||||
if (flows.length != 1) continue;
|
||||
Function target = currentProgram.getFunctionManager().getFunctionAt(flows[0]);
|
||||
if (target == null) continue;
|
||||
Function root = target.isThunk() ? target.getThunkedFunction(true) : target;
|
||||
if (root == null || !root.equals(callee)) continue;
|
||||
originalEnds.put(caller, caller.getBody().getMaxAddress());
|
||||
originalSignatures.put(caller, caller.getPrototypeString(false, true));
|
||||
callee.setNoReturn(true);
|
||||
ins.setFlowOverride(FlowOverride.CALL_RETURN);
|
||||
Address end = ins.getMaxAddress();
|
||||
clearListing(end.add(1), originalEnds.get(caller));
|
||||
caller.setBody(new AddressSet(caller.getEntryPoint(), end));
|
||||
require("truncated_" + callee.getName(), ins.getFlowType().isTerminal());
|
||||
return;
|
||||
}
|
||||
throw new IllegalStateException("Missing fixture call to " + callee.getName());
|
||||
}
|
||||
|
||||
private GhidraScript script(String name, File expected) throws Exception {
|
||||
ResourceFile source = GhidraScriptUtil.findScriptByName(name);
|
||||
if (source == null || !expected.equals(new File(source.getAbsolutePath()).getCanonicalFile()))
|
||||
throw new IllegalStateException("Fixture resolved an unexpected script: " + name);
|
||||
GhidraScript instance = GhidraScriptUtil.getProvider(source).getScriptInstance(source, errorWriter);
|
||||
instance.set(getState(), getControls());
|
||||
return instance;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() throws Exception {
|
||||
String[] args = getScriptArgs();
|
||||
if (args.length != 1) throw new IllegalArgumentException("Expected exact bridge directory");
|
||||
File directory = new File(args[0]).getCanonicalFile();
|
||||
Map<String, String> imports = Map.of(
|
||||
"rea_malloc", "malloc", "rea_tls", "__tls_get_addr",
|
||||
"rea_memcpy", "memcpy", "rea_memset", "memset",
|
||||
"rea_strlen", "strlen", "rea_errno", "__errno_location");
|
||||
for (var item : imports.entrySet()) truncate(function(item.getKey()), item.getValue());
|
||||
truncate(function("rea_tls_chain"), function("rea_tls"));
|
||||
truncate(function("rea_tls_outer"), function("rea_tls_chain"));
|
||||
function("rea_tls_outer").setNoReturn(true);
|
||||
Function adjacentCaller = function("rea_malloc_adjacent");
|
||||
truncate(adjacentCaller, "malloc");
|
||||
Address adjacentEntry = adjacentCaller.getBody().getMaxAddress().add(1);
|
||||
Function adjacent = currentProgram.getFunctionManager().createFunction(
|
||||
"rea_independent_entry", adjacentEntry,
|
||||
new AddressSet(adjacentEntry, originalEnds.get(adjacentCaller)), SourceType.USER_DEFINED);
|
||||
AddressSet adjacentBody = new AddressSet(adjacent.getBody());
|
||||
truncate(function("rea_unknown"), "rea_unknown_stop");
|
||||
external("abort").setNoReturn(true);
|
||||
external("_Unwind_Resume").setNoReturn(true);
|
||||
Function localStop = function("rea_local_stop");
|
||||
localStop.setParentNamespace(currentProgram.getSymbolTable().createNameSpace(
|
||||
currentProgram.getGlobalNamespace(), "REA_LOCAL_CONTROL", SourceType.USER_DEFINED));
|
||||
localStop.setName("malloc", SourceType.USER_DEFINED);
|
||||
localStop.setNoReturn(true);
|
||||
Function localReturn = function("rea_local_return");
|
||||
localReturn.setNoReturn(true);
|
||||
|
||||
GhidraScript fix = script("ReaGhidraNoReturnFix.java", new File(directory, "ReaGhidraNoReturnFix.java"));
|
||||
Method repair = fix.getClass().getMethod("run");
|
||||
repair.invoke(fix);
|
||||
for (String name : List.of("rea_tls", "rea_tls_chain", "rea_tls_outer")) {
|
||||
Function caller = function(name);
|
||||
require("propagated_flag_repaired_" + name, !caller.hasNoReturn());
|
||||
require("propagated_body_recovered_" + name, caller.getBody().contains(originalEnds.get(caller)));
|
||||
require("propagated_signature_preserved_" + name, caller.getPrototypeString(false, true).equals(originalSignatures.get(caller)));
|
||||
}
|
||||
for (var item : imports.entrySet()) {
|
||||
Function caller = function(item.getKey());
|
||||
require("returning_import_" + item.getValue(), !external(item.getValue()).hasNoReturn());
|
||||
require("recovered_body_" + item.getValue(), caller.getBody().contains(originalEnds.get(caller)));
|
||||
require("preserved_signature_" + item.getValue(), caller.getPrototypeString(false, true).equals(originalSignatures.get(caller)));
|
||||
}
|
||||
require("abort_preserved", external("abort").hasNoReturn());
|
||||
require("unwind_preserved", external("_Unwind_Resume").hasNoReturn());
|
||||
require("unknown_import_preserved", external("rea_unknown_stop").hasNoReturn());
|
||||
require("local_name_not_whitelisted", localStop.hasNoReturn());
|
||||
require("local_return_repaired", !localReturn.hasNoReturn());
|
||||
require("independent_entry_preserved", adjacent.getBody().equals(adjacentBody) &&
|
||||
!adjacentCaller.getBody().contains(adjacentEntry));
|
||||
|
||||
GhidraScript bridge = script("ReaGhidraBridge.java", new File(directory, "ReaGhidraBridge.java"));
|
||||
Method warnings = bridge.getClass().getDeclaredMethod("noReturnCallLimitations", Iterable.class);
|
||||
warnings.setAccessible(true);
|
||||
Object reported = warnings.invoke(bridge, currentProgram.getListing().getInstructions(function("rea_unknown").getBody(), true));
|
||||
require("unknown_boundary_named", reported instanceof List<?> values &&
|
||||
values.stream().anyMatch(value -> value.toString().contains("rea_unknown_stop") && value.toString().contains("fallthrough")));
|
||||
Object healthy = warnings.invoke(bridge, currentProgram.getListing().getInstructions(function("rea_tls").getBody(), true));
|
||||
require("healthy_boundary_no_warning", healthy instanceof List<?> values && values.isEmpty());
|
||||
Object guarded = warnings.invoke(bridge, currentProgram.getListing().getInstructions(adjacentCaller.getBody(), true));
|
||||
require("unrepaired_boundary_named", guarded instanceof List<?> values &&
|
||||
values.stream().anyMatch(value -> value.toString().contains("malloc")));
|
||||
Method initialize = bridge.getClass().getDeclaredMethod("initializeDecompiler");
|
||||
initialize.setAccessible(true);
|
||||
initialize.invoke(bridge);
|
||||
Method pseudocode = bridge.getClass().getDeclaredMethod("procedurePseudocode", JsonObject.class);
|
||||
pseudocode.setAccessible(true);
|
||||
JsonObject query = new JsonObject();
|
||||
query.addProperty("document", currentProgram.getName());
|
||||
query.addProperty("procedure", "rea_tls");
|
||||
var field = bridge.getClass().getDeclaredField("decompiler");
|
||||
field.setAccessible(true);
|
||||
try {
|
||||
Object output = pseudocode.invoke(bridge, query);
|
||||
require("recovered_pseudocode", output instanceof JsonObject value &&
|
||||
value.get("value").getAsString().contains("rea_after_call"));
|
||||
} finally {
|
||||
((ghidra.app.decompiler.DecompInterface) field.get(bridge)).dispose();
|
||||
}
|
||||
Map<Function, AddressSet> bodies = new LinkedHashMap<>();
|
||||
for (var item : imports.entrySet()) bodies.put(function(item.getKey()), new AddressSet(function(item.getKey()).getBody()));
|
||||
repair.invoke(fix);
|
||||
require("idempotent_body_repair", bodies.entrySet().stream().allMatch(item -> item.getValue().equals(item.getKey().getBody())));
|
||||
JsonObject report = new JsonObject();
|
||||
report.addProperty("status", "passed");
|
||||
report.addProperty("ghidra_version", Application.getApplicationVersion());
|
||||
report.addProperty("target_sha256", currentProgram.getExecutableSHA256());
|
||||
for (String name : List.of("ReaGhidraBridge.java", "ReaGhidraNoReturnFix.java")) {
|
||||
byte[] bytes = Files.readAllBytes(new File(directory, name).toPath());
|
||||
report.addProperty(name, HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)));
|
||||
}
|
||||
report.add("checks", checks);
|
||||
println("REA_NO_RETURN_PROBE_JSON " + report);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
|
||||
extern void *__tls_get_addr(void *);
|
||||
extern void rea_unknown_stop(void);
|
||||
extern void _Unwind_Resume(void *) __attribute__((noreturn));
|
||||
volatile unsigned long rea_after_call;
|
||||
|
||||
void *rea_malloc(size_t n) {
|
||||
void *p = malloc(n);
|
||||
rea_after_call++;
|
||||
return p;
|
||||
}
|
||||
void *rea_malloc_adjacent(size_t n) {
|
||||
void *p = malloc(n);
|
||||
rea_after_call++;
|
||||
return p;
|
||||
}
|
||||
__attribute__((visibility("hidden"))) void *rea_tls(void *p) {
|
||||
void *value = __tls_get_addr(p);
|
||||
rea_after_call++;
|
||||
return value;
|
||||
}
|
||||
__attribute__((visibility("hidden"))) void *rea_tls_chain(void *p) {
|
||||
void *value = rea_tls(p);
|
||||
rea_after_call++;
|
||||
return value;
|
||||
}
|
||||
void *rea_tls_outer(void *p) {
|
||||
void *value = rea_tls_chain(p);
|
||||
rea_after_call++;
|
||||
return value;
|
||||
}
|
||||
void *rea_memcpy(void *out, const void *in, size_t n) {
|
||||
void *value = memcpy(out, in, n);
|
||||
rea_after_call++;
|
||||
return value;
|
||||
}
|
||||
void *rea_memset(void *out, int c, size_t n) {
|
||||
void *value = memset(out, c, n);
|
||||
rea_after_call++;
|
||||
return value;
|
||||
}
|
||||
size_t rea_strlen(const char *p) {
|
||||
size_t value = strlen(p);
|
||||
rea_after_call++;
|
||||
return value;
|
||||
}
|
||||
int *rea_errno(void) {
|
||||
int *p = __errno_location();
|
||||
rea_after_call++;
|
||||
return p;
|
||||
}
|
||||
void rea_unknown(void) {
|
||||
rea_unknown_stop();
|
||||
rea_after_call++;
|
||||
}
|
||||
void rea_abort(void) { abort(); }
|
||||
void rea_unwind(void *p) { _Unwind_Resume(p); }
|
||||
void rea_local_stop(void) { __builtin_trap(); }
|
||||
int rea_local_return(void) { return 1658; }
|
||||
Reference in New Issue
Block a user