mirror of
https://github.com/morluto/rea.git
synced 2026-11-22 22:45:47 +00:00
fix(cutter/ghidra): fix Cutter DAG limit rejection, guard Ghidra x86-32 SEH scan, and cache referenced address lookups (#13478)
* fix(cutter/ghidra): fix Cutter DAG limit rejection, guard Ghidra x86-32 SEH scan, and cache referenced address lookups (#13477) * test(cutter): cover shared output and cycle rejection
This commit is contained in:
1 parent
b43084c7fd
commit
ccdc887dc1
3 files changed
+109
-36
No files matched your search
@@ -1264,12 +1264,19 @@ def _escape_json_fragment(fragment: str) -> bytes:
|
||||
return json.dumps(fragment, ensure_ascii=False)[1:-1].encode("utf-8")
|
||||
|
||||
|
||||
_CONTROL_CHAR_RE = re.compile(r"[\x00-\x1f]")
|
||||
_EXIT_CONTAINER = object()
|
||||
|
||||
|
||||
def _within_response_limit(value: Any) -> bool:
|
||||
pending = [value]
|
||||
pending: list[Any] = [value]
|
||||
seen: set[int] = set()
|
||||
size = 0
|
||||
while pending:
|
||||
current = pending.pop()
|
||||
if isinstance(current, tuple) and len(current) == 2 and current[0] is _EXIT_CONTAINER:
|
||||
seen.discard(current[1])
|
||||
continue
|
||||
if isinstance(current, str):
|
||||
size += 2
|
||||
if len(current) > MAX_FRAME_BYTES - size:
|
||||
@@ -1289,11 +1296,12 @@ def _within_response_limit(value: Any) -> bool:
|
||||
size += current.count('"') + current.count("\\")
|
||||
# A short escape is two JSON bytes and was already counted as one.
|
||||
# Other controls expand to a six-byte \\u00XX sequence.
|
||||
size += sum(
|
||||
1 if ord(character) in (0x08, 0x09, 0x0A, 0x0C, 0x0D) else 5
|
||||
for character in current
|
||||
if ord(character) < 0x20
|
||||
)
|
||||
if _CONTROL_CHAR_RE.search(current) is not None:
|
||||
size += sum(
|
||||
1 if ord(character) in (0x08, 0x09, 0x0A, 0x0C, 0x0D) else 5
|
||||
for character in current
|
||||
if ord(character) < 0x20
|
||||
)
|
||||
elif isinstance(current, dict):
|
||||
identity = id(current)
|
||||
if identity in seen:
|
||||
@@ -1305,6 +1313,7 @@ def _within_response_limit(value: Any) -> bool:
|
||||
size += 2 + count + max(0, count - 1)
|
||||
if size > MAX_FRAME_BYTES:
|
||||
return False
|
||||
pending.append((_EXIT_CONTAINER, identity))
|
||||
pending.extend(current.keys())
|
||||
pending.extend(current.values())
|
||||
elif isinstance(current, (list, tuple)):
|
||||
@@ -1317,6 +1326,7 @@ def _within_response_limit(value: Any) -> bool:
|
||||
size += 2 + max(0, count - 1)
|
||||
if size > MAX_FRAME_BYTES:
|
||||
return False
|
||||
pending.append((_EXIT_CONTAINER, identity))
|
||||
pending.extend(current)
|
||||
elif current is None:
|
||||
size += 4
|
||||
|
||||
@@ -4693,9 +4693,15 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
List.copyOf(computedCallSites));
|
||||
}
|
||||
|
||||
private boolean isX86_32Program() {
|
||||
return currentProgram.getDefaultPointerSize() == 4 &&
|
||||
"x86".equalsIgnoreCase(currentProgram.getLanguage().getProcessor().toString());
|
||||
}
|
||||
|
||||
private final class FunctionBoundaryLimitations {
|
||||
private final Function function;
|
||||
private final boolean checkLoaderRelocations = !loaderInitializedRelocations.isEmpty();
|
||||
private final boolean checkBorlandSeh = isX86_32Program();
|
||||
private final List<String> limitations = new ArrayList<>();
|
||||
private boolean inferredNoReturnCall;
|
||||
private final Set<Address> observedLoaderRelocations = new HashSet<>();
|
||||
@@ -4728,13 +4734,15 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
limitations.add(loaderInitializedRelocationLimitation(relocation));
|
||||
}
|
||||
}
|
||||
if (beforePrevious != null && previous != null) {
|
||||
String seh = borlandSehHandlerLimitation(
|
||||
function, beforePrevious, previous, instruction);
|
||||
if (seh != null) limitations.add(seh);
|
||||
if (checkBorlandSeh) {
|
||||
if (beforePrevious != null && previous != null) {
|
||||
String seh = borlandSehHandlerLimitation(
|
||||
function, beforePrevious, previous, instruction);
|
||||
if (seh != null) limitations.add(seh);
|
||||
}
|
||||
beforePrevious = previous;
|
||||
previous = instruction;
|
||||
}
|
||||
beforePrevious = previous;
|
||||
previous = instruction;
|
||||
}
|
||||
|
||||
private List<String> values() {
|
||||
@@ -5232,26 +5240,33 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
|
||||
private JsonArray referencedStrings(List<Reference> references) throws Exception {
|
||||
TreeMap<String, JsonObject> observed = new TreeMap<>();
|
||||
Map<Address, String[]> resolved = new HashMap<>();
|
||||
Listing listing = currentProgram.getListing();
|
||||
for (Reference reference : references) {
|
||||
monitor.checkCancelled();
|
||||
Data data = currentProgram.getListing().getDefinedDataContaining(
|
||||
reference.getToAddress()
|
||||
);
|
||||
if (data == null || !data.hasStringValue()) {
|
||||
continue;
|
||||
}
|
||||
String value = StringDataInstance.getStringDataInstance(data).getStringValue();
|
||||
if (value == null) {
|
||||
Address target = reference.getToAddress();
|
||||
String[] entry;
|
||||
if (resolved.containsKey(target)) {
|
||||
entry = resolved.get(target);
|
||||
} else {
|
||||
Data data = listing.getDefinedDataContaining(target);
|
||||
String value = data != null && data.hasStringValue()
|
||||
? StringDataInstance.getStringDataInstance(data).getStringValue()
|
||||
: null;
|
||||
entry = value == null ? null : new String[] { canonicalAddress(data.getAddress()), value };
|
||||
resolved.put(target, entry);
|
||||
}
|
||||
if (entry == null) {
|
||||
continue;
|
||||
}
|
||||
String sourceAddress = canonicalAddress(reference.getFromAddress());
|
||||
JsonObject item = new JsonObject();
|
||||
item.addProperty("address", canonicalAddress(data.getAddress()));
|
||||
item.addProperty("value", value);
|
||||
item.addProperty("source_address", canonicalAddress(reference.getFromAddress()));
|
||||
String key = canonicalAddress(data.getAddress()) + "\u0000" + value + "\u0000" +
|
||||
canonicalAddress(reference.getFromAddress());
|
||||
item.addProperty("address", entry[0]);
|
||||
item.addProperty("value", entry[1]);
|
||||
item.addProperty("source_address", sourceAddress);
|
||||
String key = entry[0] + "\u0000" + entry[1] + "\u0000" + sourceAddress;
|
||||
observed.put(key, item);
|
||||
}
|
||||
}
|
||||
JsonArray result = new JsonArray();
|
||||
observed.values().forEach(result::add);
|
||||
return result;
|
||||
@@ -5259,22 +5274,31 @@ public final class ReaGhidraBridge extends HeadlessScript {
|
||||
|
||||
private JsonArray referencedNames(List<Reference> references) throws Exception {
|
||||
TreeMap<String, JsonObject> observed = new TreeMap<>();
|
||||
Map<Address, String> resolved = new HashMap<>();
|
||||
SymbolTable symbolTable = currentProgram.getSymbolTable();
|
||||
for (Reference reference : references) {
|
||||
monitor.checkCancelled();
|
||||
Symbol symbol = currentProgram.getSymbolTable().getPrimarySymbol(
|
||||
reference.getToAddress()
|
||||
);
|
||||
if (symbol == null) {
|
||||
Address target = reference.getToAddress();
|
||||
String name;
|
||||
if (resolved.containsKey(target)) {
|
||||
name = resolved.get(target);
|
||||
} else {
|
||||
Symbol symbol = symbolTable.getPrimarySymbol(target);
|
||||
name = symbol == null ? null : symbol.getName(true);
|
||||
resolved.put(target, name);
|
||||
}
|
||||
if (name == null) {
|
||||
continue;
|
||||
}
|
||||
String targetAddress = canonicalAddress(target);
|
||||
String sourceAddress = canonicalAddress(reference.getFromAddress());
|
||||
JsonObject item = new JsonObject();
|
||||
item.addProperty("address", canonicalAddress(reference.getToAddress()));
|
||||
item.addProperty("value", symbol.getName(true));
|
||||
item.addProperty("source_address", canonicalAddress(reference.getFromAddress()));
|
||||
String key = canonicalAddress(reference.getToAddress()) + "\u0000" +
|
||||
symbol.getName(true) + "\u0000" + canonicalAddress(reference.getFromAddress());
|
||||
item.addProperty("address", targetAddress);
|
||||
item.addProperty("value", name);
|
||||
item.addProperty("source_address", sourceAddress);
|
||||
String key = targetAddress + "\u0000" + name + "\u0000" + sourceAddress;
|
||||
observed.put(key, item);
|
||||
}
|
||||
}
|
||||
JsonArray result = new JsonArray();
|
||||
observed.values().forEach(result::add);
|
||||
return result;
|
||||
|
||||
+39
@@ -79,6 +79,7 @@ class Dispatcher:
|
||||
def __init__(self):
|
||||
self.dispatch = self
|
||||
self.commands = []
|
||||
self.command_output = None
|
||||
self.completed_commands = {}
|
||||
self.lock = threading.Lock()
|
||||
self.command_started = threading.Event()
|
||||
@@ -113,6 +114,8 @@ class Dispatcher:
|
||||
reply.update({"ok": True, "acknowledged": self.completed_commands.pop(request["request_id"], None) is not None})
|
||||
else:
|
||||
reply.update({"ok": True, "execution_state": "complete"})
|
||||
if self.command_output is not None:
|
||||
reply["output"] = self.command_output
|
||||
if kind == "command" and isinstance(request.get("request_id"), str):
|
||||
self.completed_commands[request["request_id"]] = "complete"
|
||||
request["_event"].set()
|
||||
@@ -602,6 +605,27 @@ class ProtocolProducerTest(unittest.TestCase):
|
||||
self.assertTrue(hmac.compare_digest(frame["proof"], expected_response))
|
||||
return json.loads(response), client_nonce
|
||||
|
||||
def test_shared_command_output_round_trips_over_authenticated_socket(self):
|
||||
shared_dict = {"name": "雪"}
|
||||
shared_list = [shared_dict, shared_dict]
|
||||
shared_tuple = (shared_list, shared_list)
|
||||
self.dispatcher.command_output = [shared_tuple, shared_tuple]
|
||||
self.dispatcher.finish_command.set()
|
||||
|
||||
response, _nonce = self.exchange({
|
||||
"kind": "command",
|
||||
"session_id": self.server.session_id,
|
||||
"request_id": str(uuid.uuid4()),
|
||||
"expected_generation": self.dispatcher.generation,
|
||||
"command": "iI",
|
||||
})
|
||||
|
||||
self.assertTrue(response["ok"])
|
||||
self.assertEqual(response["execution_state"], "complete")
|
||||
expected_list = [{"name": "雪"}, {"name": "雪"}]
|
||||
self.assertEqual(response["output"], [[expected_list, expected_list]] * 2)
|
||||
self.assertNotIn("output_truncated", response)
|
||||
|
||||
def test_request_session_uuid_is_checked_after_secret_proof(self):
|
||||
spoofed = {"kind": "status", "session_id": "client-chosen-session"}
|
||||
response, _ = self.exchange(spoofed)
|
||||
@@ -1058,6 +1082,21 @@ class BridgeRequestCeilingTest(unittest.TestCase):
|
||||
overflow = {"ok": True, "output": [0] * 8000, "execution_state": "complete"}
|
||||
self.assertFalse(module._within_response_limit(overflow))
|
||||
|
||||
def test_response_preflight_refuses_direct_and_indirect_cycles(self):
|
||||
direct = []
|
||||
direct.append(direct)
|
||||
indirect = {}
|
||||
indirect["child"] = (indirect,)
|
||||
for value in (direct, indirect):
|
||||
with self.subTest(container=type(value).__name__):
|
||||
self.assertFalse(bridge._within_response_limit({"output": value}))
|
||||
|
||||
def test_response_preflight_counts_every_use_of_shared_output(self):
|
||||
module = _load_cutter_bridge("shared_output", "8192")
|
||||
shared = [0] * 2500
|
||||
self.assertTrue(module._within_response_limit({"output": shared}))
|
||||
self.assertFalse(module._within_response_limit({"output": [shared, shared]}))
|
||||
|
||||
def test_invalid_ceilings_are_refused(self):
|
||||
for raw in ("7463", "536870888", "0", "-1", "abc", "016777216", "٨١٩٢"):
|
||||
with self.assertRaises(RuntimeError) as caught:
|
||||
|
||||
Reference in new issue
Block a user