Files
nvdriver/tools/test_gpu_firmware_unpack.py

155 lines
8.8 KiB
Python

#!/usr/bin/env python3
"""Independent zlib + artifact firmware corpus against the production Rust decoder."""
from pathlib import Path
import shutil
import tempfile, subprocess, zlib, random, json, hashlib, os
R = Path(__file__).resolve().parents[1]
def q(p):
return json.dumps(str(p))
def _find_cargo() -> str:
env = os.environ.get("CARGO")
if env:
return env
found = shutil.which("cargo")
if found:
return found
cargo_home = os.environ.get("CARGO_HOME")
if cargo_home:
candidate = Path(cargo_home) / "bin" / "cargo"
if candidate.is_file():
return str(candidate)
return str(Path.home() / ".cargo/bin/cargo")
def _resolve_repo_artifact(raw_path: str) -> Path:
path = Path(raw_path)
if path.is_file():
return path
marker = "/analysis/"
if marker in raw_path:
rel = Path("analysis") / raw_path.split(marker, 1)[1]
candidate = R / rel
if candidate.is_file():
return candidate
raise FileNotFoundError(f"packed/decoded firmware artifact not found: {raw_path}")
def main() -> None:
with tempfile.TemporaryDirectory(prefix='nv-firmware-unpack-') as d:
d = Path(d)
cases = []
rng = random.Random(58017804)
patterns = [
b'a',
bytes(range(256)) * 300,
b'a' * 70000,
bytes(rng.getrandbits(8) for _ in range(66000)),
(b'gpu firmware\0' * 3000) + bytes(range(256)),
b'x' * 32768 + b'y' * 32768 + b'x' * 32768,
]
for i, pattern in enumerate(patterns):
for level in [0, 1, 6, 9]:
for strategy in [zlib.Z_DEFAULT_STRATEGY, zlib.Z_FIXED]:
c = zlib.compressobj(level, zlib.DEFLATED, -15, 8, strategy)
packed = c.compress(pattern) + c.flush()
name = f'zlib-{i}-{level}-{strategy}'
a = d / (name + '.packed')
b = d / (name + '.decoded')
a.write_bytes(packed)
b.write_bytes(pattern)
cases.append((a, b, 1))
inventory = json.loads((R / 'reports/gpu-acr-packed-inventory.json').read_text(encoding='utf-8'))
for row in inventory['records']:
cases.append((
_resolve_repo_artifact(row['packed_file']),
_resolve_repo_artifact(row['decoded_file']),
row['flags'],
))
test = '''#[path = SOURCE] mod firmware_unpack;
use firmware_unpack::*;
fn limits()->Limits{Limits{max_output:4*1024*1024,max_blocks:10000,max_symbols:4*1024*1024}}
#[test]fn independent_valid_and_partial_failure_corpus(){
let mut workspace=Workspace::new();
'''.replace('SOURCE', q(R / 'src/nvidia/src/gpu/firmware_unpack.rs'))
for a, b, flags in cases:
test += '''{let packed=include_bytes!(PACKED);let expected=include_bytes!(DECODED);let mut output=vec![0xa5;expected.len()+256];let header=Header{decoded_size:expected.len()as u32,flags:FLAGS};let decoded=unpack(header,packed,&mut output,&mut workspace,limits()).unwrap();assert_eq!(decoded.bytes(),expected.len());assert_eq!(&output[..expected.len()],expected);assert!(output[expected.len()..].iter().all(|x|*x==0xa5));assert!(decoded.input_consumed()<=packed.len());
for missing in [1,decoded.input_consumed()/2,decoded.input_consumed()]{if missing>0{let mut partial=vec![0xa5;expected.len()];assert!(unpack(header,&packed[..decoded.input_consumed()-missing],&mut partial,&mut workspace,limits()).is_err());}}
let mut partial=vec![0xa5;expected.len()];let budget=Limits{max_output:expected.len()-1,..limits()};assert_eq!(unpack(header,packed,&mut partial,&mut workspace,budget).err().unwrap().kind,Kind::OutputBounds);
}
'''.replace('PACKED', q(a)).replace('DECODED', q(b)).replace('FLAGS', str(flags))
test += '''}
#[test]fn malformed_budgets_and_roles(){let mut w=Workspace::new();let mut out=[0xa5;256];let h=Header{decoded_size:1,flags:1};assert_eq!(unpack(h,&[7],&mut out,&mut w,limits()).err().unwrap().kind,Kind::InvalidBlock);assert_eq!(unpack(h,&[1,1,0,0,0],&mut out,&mut w,limits()).err().unwrap().kind,Kind::InvalidBlock);assert_eq!(unpack(h,&[1,1,0,254,255,65],&mut out,&mut w,Limits{max_blocks:0,..limits()}).err().unwrap().kind,Kind::Budget);assert_eq!(Header{decoded_size:u32::MAX,flags:0}.allocation_size(Role::Primary),Err(Kind::OutputBounds));assert_eq!(h.allocation_size(Role::Metadata),Err(Kind::Alignment));assert_eq!(h.allocation_size(Role::Primary),Ok(256));let r=unpack(Header{flags:0,..h},&[42],&mut out,&mut w,limits()).unwrap();assert_eq!(r.bytes(),1);assert_eq!(out[0],42);assert_eq!(out[1],0xa5);}
'''
test += '\nmod registers {pub use nv_rs_core::gpu::registers::RegisterIo;}\n#[path = ' + q(R / 'src/nvidia/src/gpu/firmware_signature.rs') + '] mod firmware_signature;\n#[test] fn original_signature_instruction_vectors(){use firmware_signature::*;\n'
sig_oracle = json.loads((R / 'reports/gpu-acr-signature-oracle.json').read_text(encoding='utf-8'))
for row in sig_oracle['cases']:
base = R / 'analysis/acr-580/signature-oracle'
n = row['id']
test += '{{let mut image=*include_bytes!({});let production=include_bytes!({});let debug=include_bytes!({});let expected=include_bytes!({});let applied=apply(&mut image,production,debug,Policy{{debug_fuse:{},signature_version:{},maximum_version:{},signature_count:{},signature_bytes:{},patch_location:{},patch_index:{}}}).unwrap();assert_eq!(&image,expected);assert_eq!(applied.words,4);}}\n'.format(
q(base / f'{n}-image.bin'),
q(base / f'{n}-production.bin'),
q(base / f'{n}-debug.bin'),
q(base / f'{n}-expected.bin'),
str(row['debug_fuse']).lower(),
row['signature_version'],
row['maximum_version'],
row['signature_count'],
row['signature_bytes'],
row['patch_location'],
row['patch_index'],
)
test += 'let mut image=[0xa5;8];let p=Policy{debug_fuse:false,signature_version:0,maximum_version:0,signature_count:0,signature_bytes:4,patch_location:0,patch_index:0};assert_eq!(apply(&mut image,&[0;4],&[],p),Err(Error::ZeroCount));assert_eq!(image,[0xa5;8]);assert_eq!(apply(&mut image,&[0;3],&[],Policy{signature_count:1,..p}),Err(Error::SourceBounds));assert_eq!(image,[0xa5;8]);}\n'
test += '#[test] fn original_debug_register_read(){ struct Io(u32,bool);impl registers::RegisterIo for Io{fn read32(&mut self,offset:u32)->Result<u32,nv_rs_abi::NvStatus>{assert_eq!(offset,0x10ac08);assert!(!self.1);self.1=true;Ok(self.0)}fn write32(&mut self,_:u32,_:u32)->Result<(),nv_rs_abi::NvStatus>{panic!("unexpected write")}}'
for word, expected in sig_oracle['debug_read_vectors']:
test += 'assert_eq!(firmware_signature::read_debug_fuse(&mut Io(' + str(word) + ',false)),Ok(' + str(expected != 0).lower() + '));'
test += '}\n'
(d / 'test.rs').write_text(test, encoding='utf-8')
(d / 'Cargo.toml').write_text(
'[package]\nname="nv-firmware-corpus"\nversion="0.1.0"\nedition="2024"\n[dependencies]\nnv-rs-abi={path='
+ q(R / 'src/common/abi')
+ '}\nnv-rs-core={path='
+ q(R / 'src/nvidia')
+ '}\n[[test]]\nname="corpus"\npath="test.rs"\n',
encoding='utf-8',
)
subprocess.run([_find_cargo(), 'test', '--manifest-path', str(d / 'Cargo.toml')], check=True)
report = {
'production_source_sha256': hashlib.sha256((R / 'src/nvidia/src/gpu/firmware_unpack.rs').read_bytes()).hexdigest(),
'independent_zlib_cases': 48,
'actual_original_descriptor_cases': len(inventory['records']),
'each_valid_case_checks': [
'exact decoded bytes',
'untouched allocation padding',
'bounded consumed bytes',
'three truncation cuts rejected',
'output budget rejected',
],
'physical_gpu_access': False,
'signature_authentication': False,
'original_decoder_execution': False,
'original_signature_instruction_cases': 80,
'original_debug_read_instruction_cases': 36,
'source_sha256': {
str(p.relative_to(R)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in [
R / 'src/nvidia/src/gpu/firmware_unpack.rs',
R / 'src/nvidia/src/gpu/firmware_signature.rs',
R / 'src/nvidia/kernel/firmware.rs',
]
},
}
(R / 'reports/gpu-firmware-unpack-validation.json').write_text(
json.dumps(report, indent=2) + '\n',
encoding='utf-8',
)
print(json.dumps(report))
if __name__ == '__main__':
main()