Files
nvdriver/tools/gpu_scan_packed_firmware.py

179 lines
7.0 KiB
Python

#!/usr/bin/env python3
"""Bounded packed-descriptor scan; matches are candidates, not HAL selection."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import struct
import zlib
ROOT = Path(__file__).resolve().parents[1]
EXPECTED_SHA256 = '5269a23ffba19a17fe16f076463e7ad4151254659441d1711bee6c6221ff6f4b'
DEFAULT_ANALYSIS_ROOT = Path.home() / 'nvidia-driver/analysis-580.178.04'
def find_rm_object() -> Path:
candidates = []
if os.environ.get('NV_RS_RM_OBJECT'):
candidates.append(Path(os.environ['NV_RS_RM_OBJECT']))
if os.environ.get('NV_RS_KERNEL_SRC'):
base = Path(os.environ['NV_RS_KERNEL_SRC'])
candidates.extend([base / 'nvidia/nv-kernel.o_binary', base])
analysis = Path(os.environ.get('NV_RS_ANALYSIS_ROOT', str(DEFAULT_ANALYSIS_ROOT)))
candidates.append(analysis / 'extracted/kernel/nvidia/nv-kernel.o_binary')
candidates.extend([
Path('/usr/src/nvidia-580.178.04/nvidia/nv-kernel.o_binary'),
Path('/usr/src/nvidia-srv-580.178.04/nvidia/nv-kernel.o_binary'),
])
for candidate in candidates:
if candidate.is_file():
return candidate
raise SystemExit('Cannot find 580.178.04 nv-kernel.o_binary; set NV_RS_RM_OBJECT or NV_RS_KERNEL_SRC')
def parse_elf64(raw: bytes):
if len(raw) < 64 or raw[:4] != b'\x7fELF' or raw[4] != 2 or raw[5] != 1:
raise SystemExit('nv-kernel.o_binary is not a valid 64-bit little-endian ELF file')
e_shoff, = struct.unpack_from('<Q', raw, 40)
e_shentsize, e_shnum, e_shstrndx = struct.unpack_from('<HHH', raw, 58)
sh0 = struct.unpack_from('<IIQQQQIIQQ', raw, e_shoff)
if e_shnum == 0:
e_shnum = sh0[5]
if e_shstrndx == 0xFFFF:
e_shstrndx = sh0[6]
hdrs = [struct.unpack_from('<IIQQQQIIQQ', raw, e_shoff + i * e_shentsize) for i in range(e_shnum)]
str_off, str_size = hdrs[e_shstrndx][4], hdrs[e_shstrndx][5]
shstr = raw[str_off:str_off + str_size]
sections = []
by_name = {}
for idx, h in enumerate(hdrs):
nul = shstr.find(b'\x00', h[0])
name = shstr[h[0]:nul if nul != -1 else len(shstr)].decode('utf-8', errors='replace')
sections.append((name, h))
by_name[name] = idx
return sections, by_name
def load_symbols(raw: bytes, sections, sym_idx: int):
_, h = sections[sym_idx]
entsize = h[9] or 24
ext = None
for _, sh in sections:
if sh[1] == 18 and sh[6] == sym_idx:
ext = struct.unpack_from(f'<{sh[5] // 4}I', raw, sh[4])
break
syms = []
for i in range(h[5] // entsize):
_st_name, _st_info, _st_other, st_shndx, st_value, _st_size = struct.unpack_from('<IBBHQQ', raw, h[4] + i * entsize)
if st_shndx == 0xFFFF and ext is not None and i < len(ext):
st_shndx = ext[i]
syms.append((st_shndx, st_value))
return syms
def main(argv=None) -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--firmware-dir', type=Path, default=Path('/lib/firmware/nvidia/gv100'))
parser.add_argument('--dry-run', action='store_true', help='scan without writing output files')
args = parser.parse_args(argv)
rm_obj = find_rm_object()
raw_elf = rm_obj.read_bytes()
sha = hashlib.sha256(raw_elf).hexdigest()
if sha != EXPECTED_SHA256:
raise SystemExit(f'{rm_obj}: sha256 mismatch ({sha} != {EXPECTED_SHA256})')
out = ROOT / 'analysis/firmware-candidates'
if not args.dry_run:
out.mkdir(parents=True, exist_ok=True)
files = (
{str(p): p.read_bytes() for p in sorted(args.firmware_dir.rglob('*.bin'))}
if args.firmware_dir.is_dir()
else {}
)
sections, by_name = parse_elf64(raw_elf)
syms = load_symbols(raw_elf, sections, by_name['.symtab'])
ro = by_name['.rodata']
ro_h = sections[ro][1]
raw = raw_elf[ro_h[4]:ro_h[4] + ro_h[5]]
rel_h = sections[by_name['.rela.rodata']][1]
rel_entsize = rel_h[9] or 24
records = []
seen = set()
candidates = 0
for i in range(rel_h[5] // rel_entsize):
offset, r_info, r_addend = struct.unpack_from('<QQq', raw_elf, rel_h[4] + i * rel_entsize)
shndx, st_value = syms[r_info >> 32]
if shndx != ro or offset < 8 or offset + 16 > len(raw):
continue
size, stored = struct.unpack_from('<II', raw, offset - 8)
flags, reserved = struct.unpack_from('<II', raw, offset + 8)
storage = st_value + r_addend
if flags not in (1, 3, 11) or not (128 <= size <= 8 * 1024 * 1024) or not (8 < stored <= 8 * 1024 * 1024) or not (0 <= storage <= len(raw) - stored):
continue
key = (storage, size, stored)
if key in seen:
continue
seen.add(key)
candidates += 1
compressed = raw[storage:storage + stored]
try:
decoder = zlib.decompressobj(-15)
decoded = decoder.decompress(compressed, size + 1)
if not decoder.eof or len(decoded) != size:
continue
except zlib.error:
continue
matches = []
for name, value in files.items():
where = value.find(decoded)
if where >= 0:
matches.append({'file': name, 'decoded_in_file': where, 'whole_decoded_bytes': size})
name = f'{offset - 8 + 0x0111D660:x}'
row = {
'descriptor': hex(offset - 8 + 0x0111D660),
'decoded_size': size,
'stored_bytes': stored,
'storage': hex(storage + 0x0111D660),
'flags': flags,
'word20': reserved,
'decoded_sha256': hashlib.sha256(decoded).hexdigest(),
'installed_whole_payload_matches': matches,
}
if matches and not args.dry_run:
(out / (name + '.packed')).write_bytes(compressed)
(out / (name + '.decoded')).write_bytes(decoded)
row['packed_file'] = str(out / (name + '.packed'))
row['decoded_file'] = str(out / (name + '.decoded'))
records.append(row)
if not args.dry_run:
report_path = ROOT / 'reports/gpu-packed-firmware-candidates.json'
report_path.parent.mkdir(parents=True, exist_ok=True)
report_path.write_text(
json.dumps(
{
'artifact_sha256': sha,
'examined_candidates': candidates,
'valid_deflate_descriptors': len(records),
'records': records,
'runtime_hal_selection_proven': False,
'physical_gpu_access': False,
},
indent=2,
)
+ '\n',
encoding='utf-8',
)
print(json.dumps({'examined': candidates, 'valid': len(records), 'whole_match_descriptors': sum(bool(r['installed_whole_payload_matches']) for r in records)}))
for row in records:
if row['installed_whole_payload_matches']:
print(row['descriptor'], row['decoded_size'], row['installed_whole_payload_matches'])
if __name__ == '__main__':
main()