upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tests/test_pe_inspect.py
diff options
context:
space:
mode:
Diffstat (limited to 'tests/test_pe_inspect.py')
-rw-r--r--tests/test_pe_inspect.py346
1 files changed, 346 insertions, 0 deletions
diff --git a/tests/test_pe_inspect.py b/tests/test_pe_inspect.py
index 4c0cb1228..f9312dc1d 100644
--- a/tests/test_pe_inspect.py
+++ b/tests/test_pe_inspect.py
@@ -1383,5 +1383,351 @@ class HostClassesTest(unittest.TestCase):
1383 self.assertEqual(pe_inspect.runtime_shim_dlls(os.path.join(self.dir, "missing")), frozenset()) 1383 self.assertEqual(pe_inspect.runtime_shim_dlls(os.path.join(self.dir, "missing")), frozenset())
1384 1384
1385 1385
1386class TestExportForwarders(unittest.TestCase):
1387 def inspect_buf(self, buf: bytes) -> dict:
1388 return pe_inspect._inspect_exports(pe_inspect.PeImage(buf))
1389
1390 def test_export_rva_at_the_end_of_the_export_directory_is_not_a_forwarder(self):
1391 """The directory is [begin, end): an RVA equal to the end is past it, as in runtime/src/pe_loader.cpp."""
1392 end = 0x1800 # the export directory of with_exports() is [0x1700, 0x1800)
1393 data = with_exports([end], {0: "AtTheEnd"}, base=1)
1394 exp = self.inspect_buf(data)
1395 self.assertEqual(exp["forwarders"], {})
1396 self.assertEqual(exp["exports"], ["AtTheEnd"])
1397 last = with_exports([end - 1], {0: "LastByte"}, base=1)
1398 self.assertIn("LastByte", self.inspect_buf(last)["forwarders"])
1399
1400 def test_case1_normal_exports_and_unused_slots(self):
1401 """Case 1: Normal code exports + unused zero-RVA slot skipped (forwarders empty, invalid_export_count 0)."""
1402 data = with_exports([0x1000, 0, 0x1010], {0: "Alpha", 2: "Beta"}, base=1)
1403 exp = self.inspect_buf(data)
1404 self.assertEqual(exp["exports"], ["Alpha", "Beta"])
1405 self.assertEqual(exp["forwarders"], {})
1406 self.assertEqual(exp["invalid_export_count"], 0)
1407 self.assertEqual(exp["invalid_exports"], [])
1408
1409 def test_case2_named_forwarded_export(self):
1410 """Case 2: Named forwarded export (RVA inside export directory [0x1700, 0x1800))."""
1411 data = with_exports([0x1000, FORWARDER], {0: "NormalFunc", 1: "Sleep"}, base=10)
1412 exp = self.inspect_buf(data)
1413 self.assertEqual(exp["exports"], ["NormalFunc", "Sleep"])
1414 self.assertEqual(exp["forwarders"], {"Sleep": "other.Target"})
1415 self.assertEqual(exp["invalid_export_count"], 0)
1416
1417 with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
1418 f.write(data)
1419 f.flush()
1420 tmp_path = f.name
1421 try:
1422 report = pe_inspect.inspect(tmp_path, None)
1423 md = pe_inspect.to_markdown(report)
1424 self.assertIn("(1 forwarded)", md)
1425 self.assertIn("## Forwarded Exports", md)
1426 self.assertIn("| `Sleep` | `other.Target` |", md)
1427 finally:
1428 os.unlink(tmp_path)
1429
1430 def test_case3_ordinal_only_forwarder(self):
1431 """Case 3: Ordinal-only forwarded export (index not in named)."""
1432 data = with_exports([0x1000, FORWARDER], {0: "Func"}, base=10)
1433 exp = self.inspect_buf(data)
1434 self.assertEqual(exp["exports"], ["Func", "#11"])
1435 self.assertEqual(exp["forwarders"], {"#11": "other.Target"})
1436 self.assertEqual(exp["invalid_export_count"], 0)
1437
1438 def test_case4_aliased_named_forwarders(self):
1439 """Case 4: Two export names mapping to the same forwarded EAT index."""
1440 data = with_exports([FORWARDER], {0: "AliasA"}, base=1)
1441 buf = bytearray(data)
1442 place(buf, 0x1700, struct.pack("<IIHHIIIIIII", 0, 0, 0, 0, 0x1780, 1, 1, 2,
1443 EXPORT_FUNCS, 0x1C00, 0x1C80))
1444 place(buf, 0x1C00, struct.pack("<II", 0x1D00, 0x1D10))
1445 place(buf, 0x1C80, struct.pack("<HH", 0, 0))
1446 place(buf, 0x1D00, b"AliasA\0")
1447 place(buf, 0x1D10, b"AliasB\0")
1448 exp = self.inspect_buf(bytes(buf))
1449 self.assertEqual(exp["exports"], ["AliasA", "AliasB"])
1450 self.assertEqual(exp["forwarders"], {"AliasA": "other.Target", "AliasB": "other.Target"})
1451 self.assertEqual(exp["invalid_export_count"], 0)
1452
1453 def test_case5_out_of_bounds_export_rva(self):
1454 """Case 5: Out-of-bounds export RVA (>= size_of_image)."""
1455 data = with_exports([0x3000], {0: "BadFunc"}, base=10)
1456 exp = self.inspect_buf(data)
1457 self.assertEqual(exp["exports"], ["BadFunc"])
1458 self.assertEqual(exp["invalid_export_count"], 1)
1459 self.assertEqual(len(exp["invalid_exports"]), 1)
1460 self.assertEqual(exp["invalid_exports"][0]["symbol"], "BadFunc")
1461 self.assertEqual(exp["invalid_exports"][0]["reason"], "out_of_bounds")
1462
1463 with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
1464 f.write(data)
1465 f.flush()
1466 tmp_path = f.name
1467 try:
1468 report = pe_inspect.inspect(tmp_path, None)
1469 md = pe_inspect.to_markdown(report)
1470 self.assertIn("INVALID: 1 invalid: BadFunc (out_of_bounds)", md)
1471 finally:
1472 os.unlink(tmp_path)
1473
1474 def test_case6_unreadable_forwarder_and_error_cap(self):
1475 """Case 6: Unreadable forwarder string and invalid error cap at <= 5."""
1476 buf = bytearray(build_image())
1477 dir_entry = 0x58 + 112 + pe_inspect.DIR_EXPORT * 8
1478 struct.pack_into("<II", buf, dir_entry, 0x1700, 0x2000)
1479 place(buf, 0x1700, struct.pack("<IIHHIIIIIII", 0, 0, 0, 0, 0x1780, 1, 1, 1,
1480 EXPORT_FUNCS, 0x1C00, 0x1C80))
1481 place(buf, EXPORT_FUNCS, struct.pack("<I", 0x3500))
1482 place(buf, 0x1C00, struct.pack("<I", 0x1D00))
1483 place(buf, 0x1C80, struct.pack("<H", 0))
1484 place(buf, 0x1D00, b"BrokenFwd\0")
1485 exp = self.inspect_buf(bytes(buf))
1486 self.assertEqual(exp["forwarders"], {"BrokenFwd": "?"})
1487 self.assertEqual(exp["invalid_export_count"], 1)
1488 self.assertEqual(exp["invalid_exports"][0]["reason"], "unreadable_forwarder")
1489
1490 bad_slots = [0x4000 + i * 0x100 for i in range(8)]
1491 bad_names = {i: f"Bad{i}" for i in range(8)}
1492 data_bad = with_exports(bad_slots, bad_names, base=1)
1493 exp_bad = self.inspect_buf(data_bad)
1494 self.assertEqual(exp_bad["invalid_export_count"], 8)
1495 self.assertEqual(len(exp_bad["invalid_exports"]), 5)
1496
1497 def test_case7_combined_forwarder_and_invalid_summary(self):
1498 """Case 7: DLL with both valid forwarder and invalid export displays both in markdown."""
1499 data = with_exports([0x1000, FORWARDER, 0x3000], {1: "Fwd|Func", 2: "BadFunc"}, base=10)
1500 with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
1501 f.write(data)
1502 f.flush()
1503 tmp_path = f.name
1504 try:
1505 report = pe_inspect.inspect(tmp_path, None)
1506 md = pe_inspect.to_markdown(report)
1507 self.assertIn("(1 forwarded; INVALID: 1 invalid: BadFunc (out_of_bounds))", md)
1508 self.assertIn("| `Fwd\\|Func` | `other.Target` |", md)
1509 finally:
1510 os.unlink(tmp_path)
1511
1512 def test_case8_out_of_range_ordinal_and_small_dir_size(self):
1513 """Case 8: Ordinal index >= functions recorded as invalid, dir_size < 40 returns empty."""
1514 data = with_exports([0x1000], {0: "NormalFunc"}, base=1)
1515 buf = bytearray(data)
1516 # Point the ordinal table to index 5 while NumberOfFunctions is 1
1517 place(buf, 0x1C80, struct.pack("<H", 5))
1518 exp = self.inspect_buf(bytes(buf))
1519 self.assertNotIn("NormalFunc", exp["exports"])
1520 self.assertEqual(exp["exports"], ["#1"])
1521 self.assertEqual(exp["forwarders"], {})
1522 self.assertEqual(exp["invalid_export_count"], 1)
1523 self.assertEqual(len(exp["invalid_exports"]), 1)
1524 self.assertEqual(exp["invalid_exports"][0]["symbol"], "NormalFunc")
1525 self.assertEqual(exp["invalid_exports"][0]["ordinal"], 6)
1526 self.assertEqual(exp["invalid_exports"][0]["reason"], "out_of_range_ordinal")
1527
1528 # When slot is 0, exports is empty, but out-of-range ordinal is still recorded
1529 data_zero = with_exports([0], {0: "NormalFunc"}, base=1)
1530 buf_zero = bytearray(data_zero)
1531 place(buf_zero, 0x1C80, struct.pack("<H", 5))
1532 exp_zero = self.inspect_buf(bytes(buf_zero))
1533 self.assertEqual(exp_zero["exports"], [])
1534 self.assertEqual(exp_zero["invalid_export_count"], 1)
1535
1536 # dir_size < 40 returns empty dict
1537 dir_entry = 0x58 + 112 + pe_inspect.DIR_EXPORT * 8
1538 struct.pack_into("<II", buf, dir_entry, 0x1700, 39)
1539 exp_small = self.inspect_buf(bytes(buf))
1540 self.assertEqual(exp_small["exports"], [])
1541 self.assertEqual(exp_small["forwarders"], {})
1542 self.assertEqual(exp_small["invalid_export_count"], 0)
1543
1544 def test_case9_out_of_range_ordinal_markdown_report(self):
1545 """Case 9: Markdown report includes out_of_range_ordinal invalid export."""
1546 data = with_exports([0x1000], {0: "NormalFunc"}, base=1)
1547 buf = bytearray(data)
1548 place(buf, 0x1C80, struct.pack("<H", 5))
1549 with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
1550 f.write(buf)
1551 f.flush()
1552 tmp_path = f.name
1553 try:
1554 report = pe_inspect.inspect(tmp_path, None)
1555 md = pe_inspect.to_markdown(report)
1556 self.assertIn("INVALID: 1 invalid: NormalFunc (out_of_range_ordinal)", md)
1557 finally:
1558 os.unlink(tmp_path)
1559
1560 def test_case10_malformed_forwarder_targets(self):
1561 """Case 10: Malformed forwarder target strings recorded as malformed_forwarder."""
1562 bad_targets = [
1563 b"nodot\0",
1564 b".leadingdot\0",
1565 b"trailingdot.\0",
1566 b"other.#\0",
1567 b"other.#notanumber\0",
1568 b"other.#0\0",
1569 b"other.#70000\0",
1570 b"bad\x01target.Func\0",
1571 ]
1572 for target_bytes in bad_targets:
1573 with self.subTest(target=target_bytes):
1574 data = bytearray(with_exports([FORWARDER], {0: "TestFunc"}, base=1))
1575 place(data, FORWARDER, target_bytes)
1576 exp = self.inspect_buf(bytes(data))
1577 self.assertEqual(exp["invalid_export_count"], 1)
1578 self.assertEqual(exp["invalid_exports"][0]["symbol"], "TestFunc")
1579 self.assertEqual(exp["invalid_exports"][0]["reason"], "malformed_forwarder")
1580
1581 def test_case11_intra_module_forwarder_self_loop(self):
1582 """Case 11: Forwarder targeting itself in the same module is recorded as forwarder_loop."""
1583 # sample.dll exporting Sleep -> sample.Sleep or sample.dll.Sleep
1584 for target in (b"sample.Sleep\0", b"sample.dll.Sleep\0"):
1585 with self.subTest(target=target):
1586 data = bytearray(with_exports([FORWARDER], {0: "Sleep"}, base=1))
1587 place(data, FORWARDER, target)
1588 exp = self.inspect_buf(bytes(data))
1589 self.assertEqual(exp["invalid_export_count"], 1)
1590 self.assertEqual(exp["invalid_exports"][0]["symbol"], "Sleep")
1591 self.assertEqual(exp["invalid_exports"][0]["reason"], "forwarder_loop")
1592
1593 with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
1594 f.write(data)
1595 f.flush()
1596 tmp_path = f.name
1597 try:
1598 report = pe_inspect.inspect(tmp_path, None)
1599 md = pe_inspect.to_markdown(report)
1600 self.assertIn("INVALID: 1 invalid: Sleep (forwarder_loop)", md)
1601 finally:
1602 os.unlink(tmp_path)
1603
1604 def test_case12_intra_module_forwarder_cyclic_loop(self):
1605 """Case 12: Mutual/cyclic intra-module forwarders (Alpha -> Beta, Beta -> Alpha)."""
1606 fwd_a = 0x1790
1607 fwd_b = 0x17B0
1608 data = bytearray(with_exports([fwd_a, fwd_b], {0: "Alpha", 1: "Beta"}, base=1))
1609 place(data, fwd_a, b"sample.Beta\0")
1610 place(data, fwd_b, b"sample.Alpha\0")
1611 exp = self.inspect_buf(bytes(data))
1612 self.assertEqual(exp["invalid_export_count"], 2)
1613 symbols = {inv["symbol"] for inv in exp["invalid_exports"]}
1614 self.assertEqual(symbols, {"Alpha", "Beta"})
1615 for inv in exp["invalid_exports"]:
1616 self.assertEqual(inv["reason"], "forwarder_loop")
1617
1618 def test_case13_intra_module_forwarder_depth_limit(self):
1619 """Case 13: Forwarder chain >= 8 within the same module is detected as a loop."""
1620 # Chain F0 -> F1 -> ... -> F8
1621 slots = []
1622 names = {}
1623 base_addr = 0x1790
1624 for k in range(9):
1625 addr = base_addr + k * 11
1626 slots.append(addr)
1627 names[k] = f"F{k}"
1628 data = bytearray(with_exports(slots, names, base=1))
1629 for k in range(8):
1630 addr = base_addr + k * 11
1631 place(data, addr, f"sample.F{k+1}\0".encode())
1632 # The 9th points to an external module (valid in isolation)
1633 place(data, base_addr + 8 * 11, b"kernel32.Sleep\0")
1634
1635 exp = self.inspect_buf(bytes(data))
1636 # F0's chain length reaches 8, so F0 triggers forwarder_loop
1637 f0_inv = [inv for inv in exp["invalid_exports"] if inv["symbol"] == "F0"]
1638 self.assertEqual(len(f0_inv), 1)
1639 self.assertEqual(f0_inv[0]["reason"], "forwarder_loop")
1640
1641 def test_case14_pe_header_edge_cases(self):
1642 """Case 14: e_lfanew overlapping DOS header, SizeOfImage 0, SizeOfHeaders > SizeOfImage."""
1643 base_data = build_image()
1644
1645 # e_lfanew < 0x40
1646 data_short_nt = bytearray(base_data)
1647 struct.pack_into("<I", data_short_nt, 0x3C, 0x20)
1648 with self.assertRaisesRegex(pe_inspect.PeFormatError, "overlaps the 64-byte MS-DOS header"):
1649 pe_inspect.PeImage(bytes(data_short_nt))
1650
1651 # SizeOfImage == 0
1652 data_zero_img = bytearray(base_data)
1653 struct.pack_into("<I", data_zero_img, 0x58 + 56, 0)
1654 with self.assertRaisesRegex(pe_inspect.PeFormatError, "invalid SizeOfImage 0"):
1655 pe_inspect.PeImage(bytes(data_zero_img))
1656
1657 # SizeOfHeaders > SizeOfImage
1658 data_hdr_overflow = bytearray(base_data)
1659 struct.pack_into("<I", data_hdr_overflow, 0x58 + 60, 0x4000)
1660 with self.assertRaisesRegex(pe_inspect.PeFormatError, "exceeds SizeOfImage"):
1661 pe_inspect.PeImage(bytes(data_hdr_overflow))
1662
1663
1664class TestExceptionDirectoryArchitectureValidation(unittest.TestCase):
1665 """Clean-room unit tests ensuring non-x64 machine architectures (e.g. i386, ARM64)
1666 gracefully reject 12-byte RUNTIME_FUNCTION parsing with informative diagnostics."""
1667
1668 def test_x86_machine_exception_directory_rejected_as_non_x64(self):
1669 # 32-bit x86 image (IMAGE_FILE_MACHINE_I386 = 0x14C)
1670 data = build_image(is64=False, with_directories=True)
1671 img = pe_inspect.PeImage(data)
1672 pdata = pe_inspect._inspect_pdata(img)
1673 self.assertTrue(pdata["present"])
1674 self.assertEqual(pdata["format"], "non-x64")
1675 self.assertEqual(pdata["parsed_count"], 0)
1676 self.assertIn("x86", pdata["rejection_reason"])
1677 self.assertIn("stack-based SEH", pdata["rejection_reason"])
1678
1679 with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
1680 f.write(data)
1681 f.flush()
1682 tmp_path = f.name
1683 try:
1684 report = pe_inspect.inspect(tmp_path, None)
1685 md = pe_inspect.to_markdown(report)
1686 self.assertIn("(non-x64)", md)
1687 self.assertNotIn("(OK)", md)
1688 finally:
1689 os.unlink(tmp_path)
1690
1691 def test_arm64_machine_exception_directory_rejected_as_arm64(self):
1692 # ARM64 image (IMAGE_FILE_MACHINE_ARM64 = 0xAA64)
1693 buf = bytearray(build_image(is64=True, with_directories=True))
1694 # Change machine to ARM64 (0xAA64) at FileHeader + 0 (0x44)
1695 struct.pack_into("<H", buf, 0x44, 0xAA64)
1696 # Give 32 bytes of pdata (4 entries of 8-byte ARM64 records)
1697 dir_entry = 0x58 + 112 + pe_inspect.DIR_EXCEPTION * 8
1698 struct.pack_into("<II", buf, dir_entry, 0x1800, 32)
1699 img = pe_inspect.PeImage(bytes(buf))
1700 pdata = pe_inspect._inspect_pdata(img)
1701 self.assertTrue(pdata["present"])
1702 self.assertEqual(pdata["format"], "arm64")
1703 self.assertEqual(pdata["entry_count"], 4) # 32 // 8
1704 self.assertEqual(pdata["parsed_count"], 0)
1705 self.assertIn("ARM64", pdata["rejection_reason"])
1706 self.assertIn("8-byte", pdata["rejection_reason"])
1707
1708 with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
1709 f.write(buf)
1710 f.flush()
1711 tmp_path = f.name
1712 try:
1713 report = pe_inspect.inspect(tmp_path, None)
1714 md = pe_inspect.to_markdown(report)
1715 self.assertIn("(arm64)", md)
1716 self.assertNotIn("(OK)", md)
1717 finally:
1718 os.unlink(tmp_path)
1719
1720 def test_unknown_architecture_exception_directory_rejected(self):
1721 # ARM Thumb-2 (0x1C4)
1722 buf = bytearray(build_image(is64=False, with_directories=True))
1723 struct.pack_into("<H", buf, 0x44, 0x01C4)
1724 img = pe_inspect.PeImage(bytes(buf))
1725 pdata = pe_inspect._inspect_pdata(img)
1726 self.assertTrue(pdata["present"])
1727 self.assertIn("unsupported", pdata["format"])
1728 self.assertEqual(pdata["parsed_count"], 0)
1729 self.assertIn("unsupported machine", pdata["rejection_reason"])
1730
1731
1386if __name__ == "__main__": 1732if __name__ == "__main__":
1387 unittest.main() 1733 unittest.main()