Files
nvdriver/tools/gpu_extract_sec2_packed.py

160 lines
5.8 KiB
Python

#!/usr/bin/env python3
"""Recover bounded selected original SEC2 packed bundle storage, CPU-only.
Payloads are artifact evidence, not authenticated/ready firmware objects.
"""
import hashlib
import json
from pathlib import Path
import struct
import sys
import zlib
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT / 'tools') not in sys.path:
sys.path.insert(0, str(ROOT / 'tools'))
from _elf64_reader import (
EXPECTED_RM_OBJECT_SHA256,
STT_OBJECT,
Elf64Relocatable,
find_rm_object,
verify_rm_object_sha256,
)
BUNDLES = [0x011401D8]
def main() -> None:
obj_path = find_rm_object()
sha = verify_rm_object_sha256(obj_path, EXPECTED_RM_OBJECT_SHA256)
out = ROOT / 'analysis/sec2-580'
out.mkdir(parents=True, exist_ok=True)
elf = Elf64Relocatable.from_path(obj_path)
syms = elf.symbols()
bases = {
elf.section_index('.rodata'): 0x0111D660,
elf.section_index('.data'): 0x00F7E890,
elf.section_index('.bss'): 0x05FD2180,
elf.section_index('.text'): 0x0616F810,
}
raw = {
idx: elf.section_data(idx)
for idx in bases
if elf.section_name(idx) != '.bss'
}
rel = {}
for idx in raw:
rela_name = '.rela' + elf.section_name(idx)
if elf.has_section(rela_name):
for r_offset, r_sym, _r_type, r_addend in elf.relocations(rela_name):
rel[(idx, r_offset)] = (r_sym, r_addend)
def where(address: int) -> tuple[int, int]:
for idx, base in bases.items():
if idx in raw and base <= address < base + len(raw[idx]):
return idx, address - base
raise ValueError(hex(address))
def data(address: int, length: int) -> bytes:
idx, off = where(address)
if length < 0 or off + length > len(raw[idx]):
raise SystemExit(f'slice 0x{address:x}+{length} exceeds section bounds')
return raw[idx][off:off + length]
def ptr(address: int) -> int:
idx, off = where(address)
entry = rel.get((idx, off))
if entry is None:
return int.from_bytes(raw[idx][off:off + 8], 'little')
r_sym, r_addend = entry
sym = syms[r_sym]
return bases[sym['st_shndx']] + sym['st_value'] + r_addend
objects: dict[int, list[tuple[str, int]]] = {}
for sym in syms:
if sym['st_shndx'] in bases and sym['st_type'] == STT_OBJECT and sym['st_size'] > 0:
objects.setdefault(bases[sym['st_shndx']] + sym['st_value'], []).append(
(sym['name'], sym['st_size'])
)
records = []
for bundle in BUNDLES:
count = int.from_bytes(data(bundle, 4), 'little')
if count >= 128:
raise SystemExit(f'unexpected bundle count {count} at 0x{bundle:x}')
for index in range(count):
tag = int.from_bytes(data(bundle + 8 + index * 16, 4), 'little')
address = ptr(bundle + 16 + index * 16)
header = data(address, 24)
size, unknown, _, flags, _ = struct.unpack('<IIQII', header)
storage = ptr(address + 8)
candidates = objects.get(storage, [])
row = {
'bundle': hex(bundle),
'tag': hex(tag),
'descriptor': hex(address),
'decoded_size': size,
'word4': unknown,
'flags': flags,
'storage': hex(storage),
'storage_symbols': candidates,
}
if not candidates:
enclosing = [
(name, base, length)
for base, items in objects.items()
for name, length in items
if base <= storage < base + length
]
row['enclosing_storage_symbols'] = enclosing
stored_size = unknown if flags & 1 else size
if not (0 < stored_size < 16 * 1024 * 1024):
raise SystemExit(f'invalid stored_size {stored_size} for {row}')
compressed = data(storage, stored_size)
if flags & 1:
decoder = zlib.decompressobj(-15)
decoded = decoder.decompress(compressed) + decoder.flush()
if not decoder.eof:
raise SystemExit(f'incomplete DEFLATE stream for {row}')
consumed = len(compressed) - len(decoder.unused_data)
else:
decoded = compressed[:size]
consumed = size
if len(decoded) != size:
raise SystemExit(f'decoded size mismatch ({len(decoded)} != {size}) for {row}')
name = f'{bundle:x}-{tag:x}'
(out / (name + '.packed')).write_bytes(compressed)
(out / (name + '.decoded')).write_bytes(decoded)
row.update(
stored_bytes=len(compressed),
consumed=consumed,
decoded_sha256=hashlib.sha256(decoded).hexdigest(),
storage_sha256=hashlib.sha256(compressed).hexdigest(),
packed_file=str(out / (name + '.packed')),
decoded_file=str(out / (name + '.decoded')),
head=decoded[:32].hex(),
)
records.append(row)
report_path = ROOT / 'reports/gpu-sec2-packed-inventory.json'
report_path.parent.mkdir(parents=True, exist_ok=True)
report_path.write_text(
json.dumps(
{
'artifact_sha256': sha,
'decoder_reference': 'Python zlib raw DEFLATE; not original decoder execution',
'records': records,
'physical_gpu_access': False,
},
indent=2,
)
+ '\n',
encoding='utf-8',
)
print(json.dumps({'records': len(records), 'decoded_bytes': sum(x['decoded_size'] for x in records)}))
if __name__ == '__main__':
main()