367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
146 lines
7.6 KiB
Python
146 lines
7.6 KiB
Python
"""Verify item appearance mappings in compiled ELF bytes, never load the modules.
|
|
|
|
Generated headers can advance independently of the installed native core. Every
|
|
published default appearance therefore needs the same item-to-link pair in the
|
|
actual native world translator and item codec selected for publication.
|
|
"""
|
|
import hashlib
|
|
from pathlib import Path
|
|
import struct
|
|
|
|
SYMBOL = b'_ZN7gateway19item_render_profile15ItemAppearancesE'
|
|
MAX_MODULE_BYTES = 134217728
|
|
MAX_PAIRS = 131072
|
|
MAX_SYMBOLS = 2000000
|
|
|
|
|
|
def compiled_item_appearances(path):
|
|
"""Read one bounded, defined OBJECT symbol through a read-only ELF load."""
|
|
path = Path(path)
|
|
if path.is_symlink() or not path.is_file() or not 64 <= path.stat().st_size <= MAX_MODULE_BYTES:
|
|
raise ValueError('Compiled item render profile requires a bounded regular ELF module')
|
|
with path.open('rb') as stream:
|
|
raw = stream.read(MAX_MODULE_BYTES + 1)
|
|
if not 64 <= len(raw) <= MAX_MODULE_BYTES:
|
|
raise ValueError('Compiled item render module size changed')
|
|
header = struct.unpack_from('<16sHHIQQQIHHHHHH', raw)
|
|
ident, kind, machine, version, _, phoff, shoff, _, ehsize, phsize, phnum, shsize, shnum, _ = header
|
|
if (ident[:7] != b'\x7fELF\x02\x01\x01' or (kind, machine, version) != (3, 62, 1)
|
|
or ehsize != 64 or phsize != 56 or shsize != 64
|
|
or not 0 < phnum <= 4096 or not 0 < shnum <= 8192):
|
|
raise ValueError('Compiled item render profile requires ordinary x64 little-endian ELF headers')
|
|
|
|
def span(offset, length):
|
|
if not 0 <= offset <= len(raw) or not 0 <= length <= len(raw) - offset:
|
|
raise ValueError('Compiled item render ELF range exceeds file')
|
|
return raw[offset:offset + length]
|
|
|
|
span(phoff, phsize * phnum)
|
|
span(shoff, shsize * shnum)
|
|
sections = [struct.unpack_from('<IIQQQQIIQQ', raw, shoff + n * shsize) for n in range(shnum)]
|
|
# Prefer the full symbol table; a normal ELF also repeats exported symbols
|
|
# in DYNSYM. Count definitions in exactly one table namespace, not both.
|
|
tables = [s for s in sections if s[1] == 2]
|
|
if not tables:
|
|
tables = [s for s in sections if s[1] == 11]
|
|
found = []
|
|
inspected = 0
|
|
for table in tables:
|
|
_, _, _, _, offset, size, link, _, _, entry_size = table
|
|
if entry_size != 24 or size % 24 or not 0 <= link < len(sections):
|
|
raise ValueError('Malformed compiled item render symbol table')
|
|
inspected += size // 24
|
|
if inspected > MAX_SYMBOLS:
|
|
raise ValueError('Compiled item render symbol count exceeds bound')
|
|
strings = sections[link]
|
|
if strings[1] != 3:
|
|
raise ValueError('Compiled item render symbol names require STRTAB')
|
|
names = span(strings[4], strings[5])
|
|
span(offset, size)
|
|
for n in range(size // 24):
|
|
name, info, _, section_index, value, symbol_size = struct.unpack_from('<IBBHQQ', raw, offset + n * 24)
|
|
if name >= len(names):
|
|
raise ValueError('Compiled item render symbol name exceeds table')
|
|
if (names[name:name + len(SYMBOL) + 1] == SYMBOL + b'\0' and section_index != 0):
|
|
found.append((info, section_index, value, symbol_size))
|
|
if len(found) != 1:
|
|
raise ValueError('Exactly one defined compiled ItemAppearances symbol required: ' + str(path))
|
|
info, section_index, address, size = found[0]
|
|
if (info & 15) != 1 or not 0 < section_index < len(sections):
|
|
raise ValueError('Compiled ItemAppearances must be a defined ELF OBJECT')
|
|
section = sections[section_index]
|
|
if section[1] != 1 or not (section[2] & 2) or section[2] & 5:
|
|
raise ValueError('Compiled ItemAppearances must occupy read-only allocated data')
|
|
if not 0 < size <= MAX_PAIRS * 8 or size % 8:
|
|
raise ValueError('Compiled ItemAppearances size is not a bounded pair array')
|
|
if address < section[3] or address + size > section[3] + section[5]:
|
|
raise ValueError('Compiled ItemAppearances exceeds its data section')
|
|
loads = []
|
|
for n in range(phnum):
|
|
ptype, flags, offset, vaddr, _, filesz, memsz, _ = struct.unpack_from('<IIQQQQQQ', raw, phoff + n * phsize)
|
|
if ptype != 1:
|
|
continue
|
|
if filesz > memsz:
|
|
raise ValueError('Malformed compiled item render ELF load size')
|
|
span(offset, filesz)
|
|
if vaddr <= address and address + size <= vaddr + filesz:
|
|
loads.append((flags, offset + address - vaddr))
|
|
if len(loads) != 1 or not (loads[0][0] & 4) or loads[0][0] & 2:
|
|
raise ValueError('Compiled ItemAppearances requires one read-only file-backed PT_LOAD')
|
|
offset = loads[0][1]
|
|
if offset != section[4] + address - section[3]:
|
|
raise ValueError('Compiled ItemAppearances section/load mappings disagree')
|
|
payload = span(offset, size)
|
|
pairs = list(struct.iter_unpack('<II', payload))
|
|
if (any(not 0 < item < 2**31 or not 0 < appearance < 2**31 for item, appearance in pairs)
|
|
or any(a[0] >= b[0] for a, b in zip(pairs, pairs[1:]))):
|
|
raise ValueError('Compiled ItemAppearances requires positive strictly sorted item/link pairs')
|
|
return dict(pairs=dict(pairs), receipt=dict(module=str(path), module_sha256=hashlib.sha256(raw).hexdigest(),
|
|
item_count=len(pairs), array_sha256=hashlib.sha256(payload).hexdigest(),
|
|
symbol_address=hex(address), symbol_bytes=size))
|
|
|
|
|
|
def default_appearance_requirements(package):
|
|
requirements = {}
|
|
for row in package['rows']:
|
|
if row.get('table_name') != 'ItemModifiedAppearance':
|
|
continue
|
|
status = row.get('record_status', 'valid')
|
|
if status not in ('valid', 'removed'):
|
|
raise ValueError('Published item appearance record status is malformed')
|
|
if status == 'removed':
|
|
continue
|
|
record = row.get('record')
|
|
if not isinstance(record, dict) or type(record.get('ItemAppearanceModifierID')) is not int:
|
|
raise ValueError('Published item appearance modifier identity is malformed')
|
|
if record['ItemAppearanceModifierID'] != 0:
|
|
continue
|
|
item, link = record.get('ItemID'), row.get('id')
|
|
if (any(type(value) is not int or not 0 < value < 2**31 for value in (item, link))
|
|
or type(record.get('ID')) is not int or record['ID'] != link):
|
|
raise ValueError('Published default item appearance identity is malformed')
|
|
if item in requirements:
|
|
raise ValueError('Published item has multiple default appearance links: ' + str(item))
|
|
requirements[item] = link
|
|
return requirements
|
|
|
|
|
|
def verify_compiled_item_render_profiles(package, native_core, codec):
|
|
"""Fail closed before installation when either compiled consumer is stale."""
|
|
expected = default_appearance_requirements(package)
|
|
if not expected:
|
|
return None
|
|
result = dict(required_default_items=len(expected),
|
|
check_scope='Every nonremoved ItemModifiedAppearance with modifier 0: exact ItemID-to-row-ID in both compiled consumers',
|
|
engine_rendering_verified=False)
|
|
for label, path in (('native_core', native_core), ('codec', codec)):
|
|
compiled = compiled_item_appearances(path)
|
|
mismatches = [(item, link, compiled['pairs'].get(item)) for item, link in sorted(expected.items())
|
|
if compiled['pairs'].get(item) != link]
|
|
if mismatches:
|
|
raise ValueError('Stale compiled item render profile in ' + label + ': '
|
|
+ str(len(mismatches)) + ' default mappings differ; (item, expected, compiled) '
|
|
+ repr(mismatches[:8]))
|
|
result[label] = compiled['receipt']
|
|
return result
|