diff --git a/tests/test_hashdict.py b/tests/test_hashdict.py index fbe189cc6..2a476361f 100644 --- a/tests/test_hashdict.py +++ b/tests/test_hashdict.py @@ -127,6 +127,28 @@ class LookupCLITest(unittest.TestCase): text=True, ) + def test_lookup_rejects_a_dictionary_that_is_not_an_object(self): + # #1034: a JSON array is one error line naming the file, not an AttributeError traceback + bad = os.path.join(self.tmp.name, "list.json") + with open(bad, "w", encoding="utf-8") as f: + f.write("[]") + p = self.run_tool("--lookup", bad, "0x1") + self.assertEqual(p.returncode, 2) + self.assertIn("list.json", p.stderr) + self.assertNotIn("Traceback", p.stderr) + + def test_build_rejects_a_malformed_archive_index(self): + # #1043: a bad //index.json is one ERROR line and exit 2, not a JSONDecodeError traceback + for body in ("not json", "[]", '{"files": 3}', '{"other": []}'): + with self.subTest(body=body), tempfile.TemporaryDirectory() as carve: + os.makedirs(os.path.join(carve, "arch")) + with open(os.path.join(carve, "arch", "index.json"), "w", encoding="utf-8") as f: + f.write(body) + p = self.run_tool(carve, "--out", os.path.join(carve, "out.json")) + self.assertEqual(p.returncode, 2, p.stderr) + self.assertIn("ERROR: cannot read", p.stderr) + self.assertNotIn("Traceback", p.stderr) + def test_lookup_known_hashes(self): p = self.run_tool("--lookup", self.hashes_file, "0xb779a091", "88f08ef3") self.assertEqual(p.returncode, 0, p.stderr) diff --git a/tools/hashdict.py b/tools/hashdict.py index a7aba0c34..106d3c67f 100644 --- a/tools/hashdict.py +++ b/tools/hashdict.py @@ -64,6 +64,9 @@ def main(): print(f"ERROR: cannot read the dictionary {a.lookup[0]}: {getattr(e, 'strerror', None) or e}", file=sys.stderr) return 2 + if not isinstance(d, dict): + print(f"ERROR: the dictionary {a.lookup[0]} is not a JSON object of hash -> name", file=sys.stderr) + return 2 for h, v in values: print(h, d.get(f"{v:08x}", "?")) return 0 @@ -80,8 +83,15 @@ def main(): p = os.path.join(a.carve, arch, "index.json") if not os.path.isfile(p): continue - with open(p, encoding="utf-8") as f: - rows = json.load(f)["files"] + try: + with open(p, encoding="utf-8") as f: + rows = json.load(f)["files"] + if not isinstance(rows, list) or not all(isinstance(r, dict) for r in rows): + raise ValueError('"files" is not a list of entries') + except (OSError, ValueError, KeyError, TypeError) as e: + reason = getattr(e, "strerror", None) or (f"no {e} key" if isinstance(e, KeyError) else e) + print(f"ERROR: cannot read {p}: {reason}", file=sys.stderr) + return 2 for r in rows: if r.get("type") == "bink2": continue