#!/usr/bin/env python3 """Read an XCI or NSP in place; extract and verify its base or explicitly selected update Program ExeFS. Supports NCA3, key-area or common-ticket AES-CTR, and hierarchical SHA-256 PFS0. Keys stay in memory. No RomFS extraction, executable launch, or network calls. """ import argparse import hashlib import json import struct import io from pathlib import Path from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes def require(condition, message): if not condition: raise ValueError(message) def decrypt(key, mode, data): ctx = Cipher(algorithms.AES(key), mode).decryptor() return ctx.update(data) + ctx.finalize() def read_at(f, offset, length): require(0 <= offset and 0 <= length <= 512 * 1024 * 1024, 'Invalid/big read') f.seek(offset) data = f.read(length) require(len(data) == length, 'Truncated input') return data def hfs(f, offset, bound): return partition_entries(f, offset, bound, b'HFS0', 64) def partition_entries(f, offset, bound, magic=b'PFS0', stride=24): """Read a bounded PFS0/HFS0 table without loading its file payloads.""" require(bound >= 16, 'Truncated partition header') hdr = read_at(f, offset, 16) require(hdr[:4] == magic, f'Expected {magic.decode()}') count, strings_size = struct.unpack_from('= 0, 'Unterminated partition filename') name = strings[nameoff:end].decode('utf-8') require(name not in ('', '.', '..') and '/' not in name and '\\' not in name, 'Unsafe partition filename') require(name not in names, 'Duplicate partition filename') names.add(name) require(size + off + length <= bound, 'Partition entry out of bounds') entries.append((name, offset + size + off, length)) end = offset + size for _, start, length in sorted(entries, key=lambda e: e[1]): require(start >= end, 'Overlapping partition entries') end = start + length return entries def container_entries(f, size): if read_at(f, 0, 4) == b'PFS0': return 'nsp', partition_entries(f, 0, size) require(size >= 0x138 and read_at(f, 0x100, 4) == b'HEAD', 'Expected an XCI or NSP (PFS0) game file') root = struct.unpack('= 4, 'Truncated NSP ticket') # Switch ticket signature type is little-endian: RSA2048/SHA256 = 04 00 01 00. sig = struct.unpack('= body + 0x180, 'Truncated NSP ticket body') data = read_at(f, offset + body, 0x180) require(data[0x141] == 0, 'Personalized NSP tickets are unsupported; a common ticket is required') rights, key = data[0x160:0x170], data[0x40:0x50] require(rights not in tickets or tickets[rights] == key, 'Conflicting NSP tickets') tickets[rights] = key return tickets def read_nca_header(f, offset, size, keys): require(size >= 0xc00, 'Truncated NCA header') require('header_key' in keys, 'Missing header_key in prod.keys') raw = read_at(f, offset, 0xc00) hdr = b''.join(decrypt(keys['header_key'], modes.XTS(i.to_bytes(16, 'big')), raw[i * 512:(i + 1) * 512]) for i in range(6)) require(hdr[0x200:0x204] == b'NCA3', 'Expected NCA3 (check prod.keys and the game file)') require(struct.unpack_from(' 0 and pfssize <= 512 * 1024 * 1024, 'Unsupported ExeFS hash layout') def section_read(relative, size): require(relative >= 0 and relative + size <= secsize, 'Section read out of bounds') absolute = secstart + relative aligned = absolute & ~15 iv = fs[0x140:0x148][::-1] + (aligned // 16).to_bytes(8, 'big') data = read_at(f, record_offset(record) + aligned, size + absolute - aligned) return decrypt(ctr_key, modes.CTR(iv), data)[absolute - aligned:] hashes = section_read(hashoff, hashsize) require(hashlib.sha256(hashes).digest() == fs[8:40], 'ExeFS hash-table mismatch') pfs = section_read(pfsoff, pfssize) for index, pos in enumerate(range(0, pfssize, blocksize)): expected = hashes[index * 32:(index + 1) * 32] require(hashlib.sha256(pfs[pos:pos + blocksize]).digest() == expected, f'ExeFS block hash mismatch: {index}') files = [(name, pfs[off:off + size]) for name, off, size in partition_entries(io.BytesIO(pfs), 0, len(pfs))] require(any(name == 'main.npdm' for name, _ in files), 'PFS0 is not ExeFS') args.output.mkdir(parents=True) extracted = [] for name, data in files: (args.output / name).write_bytes(data) extracted.append({'name': name, 'size': len(data), 'sha256': hashlib.sha256(data).hexdigest()}) manifest = {'source': str(args.game.resolve()), 'source_size': args.game.stat().st_size, 'source_mtime_ns': args.game.stat().st_mtime_ns, 'container': kind, 'nca_inventory': [r for r, _ in records], 'program': record, 'section_index': i, 'integrity': 'FS header, ExeFS hash table, and every ExeFS data block verified; RSA signatures not checked', 'files': extracted} (args.output.parent / 'extraction-manifest.json').write_text(json.dumps(manifest, indent=2) + '\n') print(json.dumps({'integrity': manifest['integrity'], 'files': extracted}, indent=2)) return raise ValueError('No ExeFS section found') if __name__ == '__main__': main()