#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Census of the No-Intro Nintendo 3DS sets: counts, sizes, encryption state, firmware. Reads the sets in place from $NO_INTRO_DIR (never copies, never extracts, never decrypts). - The two cartridge sets ("Nintendo 3DS (Decrypted)", "New Nintendo 3DS (Decrypted)"): for each .3ds (CCI) member only the first bytes of the deflate stream are inflated in memory, enough for the NCSD header (offset 0) and the first partition's NCCH header. From those it records (field layout: GBATEK "3DS Files - NCSD Format", "NCCH Format"; DOC): the image size, which of the eight partitions are present (0 game CXI, 1 manual, 2 Download Play child, 6 New3DS update, 7 Old3DS update), and from partition 0's NCCH header the flags byte 18Fh (bit 2 NoCrypto, bit 0 FixedKey), the 2nd-keyslot byte 18Bh and the platform byte 18Ch (1 CTR, 2 Snake = New3DS); and from the exheader (in the clear in these sets) the New3DS bytes at NCCH+40Ch/40Dh: Flag1 (bit0 EnableL2Cache, bit1 cpuspeed_804MHz) and Flag2 bits 0-3 (New3DS system mode) (DOC: GBATEK "NCCH Extended Header"). Whether an image is encrypted is read from the NoCrypto flag and checked against the ExeFS header's first file name (".code" in the clear means the ExeFS is not encrypted): reading, not decrypting. - The CDN set ("Nintendo 3DS (Digital) (CDN)"): only the zip directory is read: member names (contents 00000000.., tmd.N, cetk) and sizes. For a small sample the first content's bytes 100h-103h are inflated to see whether "NCCH" is in the clear (CDN contents are AES-CBC encrypted with the title key: DOC, GBATEK "Title Ticket"). - [BIOS] zips: each member's size and SHA-1, hashed in memory; nothing is written. In the cartridge set these are the two boot ROMs. In the CDN set they are Nintendo's system titles (applications, applets, data archives: console firmware); their SHA-1s are hashed only with --firmware (about 6 GiB to inflate), into census-firmware-3ds.txt. NO_INTRO_DIR=... python -I scripts/census_nointro.py NO_INTRO_DIR=... python -I scripts/census_nointro.py --firmware Writes tests/detectors/census-nointro-3ds.txt (one line per image plus a summary). """ from __future__ import annotations import collections import hashlib import os import random import struct import sys import zipfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] OUT = ROOT / "tests" / "detectors" / "census-nointro-3ds.txt" CART_SETS = [ "Nintendo - Nintendo 3DS (Decrypted)", "Nintendo - New Nintendo 3DS (Decrypted)", ] CDN_SET = "Nintendo - Nintendo 3DS (Digital) (CDN)" MEDIA = 0x200 PART_NAMES = {0: "game", 1: "manual", 2: "dlp-child", 6: "n3ds-update", 7: "o3ds-update"} def read_prefix(archive: zipfile.ZipFile, info: zipfile.ZipInfo, length: int) -> bytes: with archive.open(info) as handle: return handle.read(length) def parse_cci(head: bytes) -> dict: if head[0x100:0x104] != b"NCSD": return {"error": "no NCSD magic"} parts = [] for index in range(8): offset, size = struct.unpack_from(" base + 0x40D else None, flag2=head[base + 0x40D] if len(head) > base + 0x40D else None, ) return result def exefs_first_name(archive: zipfile.ZipFile, info: zipfile.ZipInfo, at: int) -> bytes: data = read_prefix(archive, info, at + 0x10) return data[at:at + 8].rstrip(b"\0") def census_carts(set_dir: Path, lines: list[str], summary: dict, bios: list[str]) -> None: for name in sorted(os.listdir(set_dir)): path = set_dir / name with zipfile.ZipFile(path) as archive: for info in archive.infolist(): if name.startswith("[BIOS]"): digest = hashlib.sha1(archive.read(info)).hexdigest() bios.append(f"{set_dir.name} | {name} | {info.filename} | {info.file_size} | sha1 {digest}") continue ext = info.filename.rsplit(".", 1)[-1].lower() summary["ext"][ext] += 1 summary["bytes"] += info.file_size if ext != "3ds": lines.append(f"{info.filename} | {info.file_size} | not a .3ds member") continue cci = parse_cci(read_prefix(archive, info, 0x5000)) if "error" in cci: summary["errors"] += 1 lines.append(f"{info.filename} | {info.file_size} | {cci['error']}") continue name0 = b"?" if cci["exefs"]: name0 = exefs_first_name(archive, info, cci["base"] + cci["exefs"]) summary["nocrypto"][cci["nocrypto"]] += 1 summary["exefs_clear"][name0 == b".code"] += 1 summary["platform"][cci["platform"]] += 1 summary["keyslot2"][cci["keyslot2"]] += 1 summary["n3ds"][(cci["flag1"], cci["flag2"])] += 1 for index in cci["parts"]: summary["parts"][PART_NAMES.get(index, str(index))] += 1 summary["size"][info.file_size] += 1 parts = ",".join(PART_NAMES.get(i, str(i)) for i in cci["parts"]) lines.append( f"{info.filename} | {info.file_size} | {cci['product']} | platform {cci['platform']}" f" | nocrypto {int(cci['nocrypto'])} | keyslot2 {cci['keyslot2']:02X}h" f" | exefs[0] {name0.decode('ascii', 'replace')} | parts {parts}" f" | n3ds flag1 {cci['flag1']} flag2 {cci['flag2']}" ) def census_cdn(set_dir: Path, lines: list[str], summary: dict) -> None: names = sorted(os.listdir(set_dir)) sample = set(random.Random(3).sample(names, min(40, len(names)))) for name in names: with zipfile.ZipFile(set_dir / name) as archive: members = archive.infolist() kinds = collections.Counter() total = 0 for info in members: base = info.filename.rsplit("/", 1)[-1] kind = "tmd" if base.startswith("tmd") else "cetk" if base.startswith("cetk") else ( "content" if len(base) == 8 and all(c in "0123456789abcdefABCDEF" for c in base) else "other") kinds[kind] += 1 total += info.file_size summary["titles"] += 1 summary["bytes"] += total summary["with_cetk"] += bool(kinds["cetk"]) summary["with_tmd"] += bool(kinds["tmd"]) summary["contents"][kinds["content"]] += 1 summary["other"] += kinds["other"] summary["dsiware"] += "(DSiWare)" in name clear = "-" if name in sample: first = next((i for i in members if i.filename.rsplit("/", 1)[-1] == "00000000"), None) if first is not None: head = read_prefix(archive, first, 0x104) clear = "yes" if head[0x100:0x104] == b"NCCH" else "no" summary["sample_clear"][clear] += 1 lines.append(f"{name} | {total} | contents {kinds['content']} | tmd {kinds['tmd']}" f" | cetk {kinds['cetk']} | NCCH magic in clear: {clear}") def firmware(root: str) -> int: set_dir = Path(root) / CDN_SET out = ["# SHA-1 of every member of the CDN set's [BIOS] zips (Nintendo system titles)", "# hashed in memory by scripts/census_nointro.py --firmware; never copied", ""] for name in sorted(n for n in os.listdir(set_dir) if n.startswith("[BIOS]")): with zipfile.ZipFile(set_dir / name) as archive: for info in archive.infolist(): digest = hashlib.sha1() with archive.open(info) as handle: for block in iter(lambda: handle.read(1 << 20), b""): digest.update(block) out.append(f"{name} | {info.filename} | {info.file_size} | sha1 {digest.hexdigest()}") target = OUT.with_name("census-firmware-3ds.txt") target.write_text("\n".join(out) + "\n", encoding="utf-8") print(f"{len(out) - 3} members hashed to {target.relative_to(ROOT)}") return 0 def main() -> int: root = os.environ.get("NO_INTRO_DIR") if not root: print("set NO_INTRO_DIR (the No-Intro sets' root)", file=sys.stderr) return 2 if "--firmware" in sys.argv[1:]: return firmware(root) out: list[str] = ["# Census of the No-Intro Nintendo 3DS sets (scripts/census_nointro.py)", ""] bios: list[str] = [] for set_name in CART_SETS: set_dir = Path(root) / set_name if not set_dir.is_dir(): out.append(f"## {set_name}: MISSING") continue summary = {"ext": collections.Counter(), "bytes": 0, "errors": 0, "nocrypto": collections.Counter(), "exefs_clear": collections.Counter(), "platform": collections.Counter(), "keyslot2": collections.Counter(), "parts": collections.Counter(), "size": collections.Counter(), "n3ds": collections.Counter()} lines: list[str] = [] census_carts(set_dir, lines, summary, bios) out.append(f"## {set_name}") out.append(f"members by extension: {dict(summary['ext'])}; total {summary['bytes'] / 2**40:.2f} TiB") out.append(f"NCCH NoCrypto flag set: {summary['nocrypto'][True]}, clear: {summary['nocrypto'][False]}") out.append(f"ExeFS first name '.code' in the clear: {summary['exefs_clear'][True]}, not: {summary['exefs_clear'][False]}") out.append(f"platform byte (1 CTR, 2 Snake/New3DS): {dict(summary['platform'])}") out.append(f"2nd keyslot byte: {dict((f'{k:02X}h', v) for k, v in summary['keyslot2'].items())}") out.append(f"partitions present: {dict(summary['parts'])}") out.append("exheader New3DS (Flag1, Flag2): " + ", ".join( f"({a}, {b}) x{n}" for (a, b), n in sorted(summary["n3ds"].items(), key=str))) out.append("image sizes: " + ", ".join(f"{size // 2**20} MiB x{n}" for size, n in sorted(summary["size"].items()))) out.append(f"header errors: {summary['errors']}") out.append("") out.extend(lines) out.append("") set_dir = Path(root) / CDN_SET if set_dir.is_dir(): summary = {"titles": 0, "bytes": 0, "with_cetk": 0, "with_tmd": 0, "contents": collections.Counter(), "other": 0, "dsiware": 0, "sample_clear": collections.Counter()} lines = [] census_cdn(set_dir, lines, summary) out.append(f"## {CDN_SET}") out.append(f"titles {summary['titles']} (DSiWare {summary['dsiware']}); total {summary['bytes'] / 2**40:.2f} TiB") out.append(f"with tmd: {summary['with_tmd']}; with cetk (ticket): {summary['with_cetk']}; other members: {summary['other']}") out.append(f"content counts per title: {dict(sorted(summary['contents'].items()))}") out.append(f"sample of first contents with 'NCCH' in the clear at 100h: {dict(summary['sample_clear'])}") out.append("") out.extend(lines) out.append("") out.append("## Firmware ([BIOS] entries; hashed in memory, never copied)") out.extend(bios or ["none"]) OUT.parent.mkdir(parents=True, exist_ok=True) OUT.write_text("\n".join(out) + "\n", encoding="utf-8") keys = ("##", "members", "NCCH", "ExeFS", "platform", "2nd", "partitions", "exheader", "image", "header", "titles", "with", "content", "sample") print("\n".join(line for line in out if line.startswith(keys) or "[BIOS]" in line)) return 0 if __name__ == "__main__": sys.exit(main())