#!/usr/bin/env python3 """Verify all six IVFC levels, stream a local RomFS image, and index its files.""" import argparse import hashlib import json import struct from pathlib import Path from cryptography.hazmat.primitives.ciphers import modes from extract_exefs import (decrypt, read_at, require, load_keys, container_entries, common_tickets, nca_inventory, program_nca, nca_ctr_key, record_offset) def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--keys',type=Path,required=True) parser.add_argument('--manifest',type=Path,default=Path('extracted/v0/extraction-manifest.json')) parser.add_argument('--output',type=Path,default=Path('extracted/v0/romfs')) args=parser.parse_args(); require(not args.output.exists(),'Output already exists') manifest=json.loads(args.manifest.read_text());record=manifest['program'];keys=load_keys(args.keys) source=Path(manifest['source']);require(source.stat().st_size==manifest['source_size'],'Source size changed') with source.open('rb') as f: _,entries=container_entries(f,source.stat().st_size) actual,hdr=program_nca(nca_inventory(f,entries,keys)) require(actual['name']==record['name'] and actual['size']==record['size'] and record_offset(actual)==record_offset(record),'Source Program NCA changed; extract ExeFS again') ctr_key=nca_ctr_key(hdr,keys,common_tickets(f,entries)) for i in range(4): start,end=struct.unpack_from('=(size+block-1)//block*32,'IVFC parent size') captured=bytearray() if level<5 else None index=0 for pos in range(0,size,8*1024*1024): chunk=read(offset+pos,min(8*1024*1024,size-pos)) for j in range(0,len(chunk),block): payload=chunk[j:j+block] require(hashlib.sha256(payload+bytes(block-len(payload))).digest()==parent[index*32:index*32+32],f'IVFC level {level} block {index} failed') index+=1 if captured is not None:captured.extend(chunk) else:image.write(chunk);digest.update(chunk) counts.append(index) if captured is not None:parent=bytes(captured) print(f'IVFC level {level}: {index} blocks verified',flush=True) files=index_romfs(image_path) report=dict(status='pass',source_size=source.stat().st_size,program=record['name'],section=i,ivfc_blocks=counts,romfs_size=levels[-1][1],romfs_sha256=digest.hexdigest(),files=files,integrity='FS header and all six IVFC levels verified; RSA signature not checked') (args.output/'index.json').write_text(json.dumps(report,indent=2)+'\n') print(json.dumps(dict(status='pass',file_count=len(files),size=levels[-1][1],sha256=digest.hexdigest())),flush=True);return raise ValueError('No supported RomFS found') def index_romfs(path): with path.open('rb') as f: h=struct.unpack('<10Q',read_at(f,0,80));require(h[0]==80,'RomFS header');length=path.stat().st_size for off,size in [(h[1],h[2]),(h[3],h[4]),(h[5],h[6]),(h[7],h[8])]:require(off+size<=length,'RomFS table bounds') dirs=read_at(f,h[3],h[4]);entries=read_at(f,h[7],h[8]);files=[];seen_dirs=set();seen_files=set();paths=set() def name(table,off,n): require(off+n<=len(table),'Name bounds');s=table[off:off+n].decode('utf-8');require(s not in ['.','..'] and '/' not in s and '\\' not in s and '\0' not in s,'Unsafe path');return s todo=[(0,'')] while todo: off,parent=todo.pop();require(off not in seen_dirs and off+24<=len(dirs),'Invalid/cyclic directory');seen_dirs.add(off) p,sibling,child,file,hash_next,n=struct.unpack_from('<6I',dirs,off);part=name(dirs,off+24,n);prefix=parent+part+'/' if part else parent if sibling!=0xffffffff:todo.append((sibling,parent)) if child!=0xffffffff:todo.append((child,prefix)) while file!=0xffffffff: require(file not in seen_files and file+32<=len(entries),'Invalid/cyclic file');seen_files.add(file) p,next_file,data,size,hash_next,n=struct.unpack_from('