diff --git a/.gitignore b/.gitignore index e717b9a..44e38d7 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,9 @@ artifacts/ *.XMF *.xmd *.XMD +*.xmp +*.XMP +*.nac +*.NAC +*.sdl +*.SDL diff --git a/README.md b/README.md index eba184f..8301ba3 100644 --- a/README.md +++ b/README.md @@ -197,6 +197,123 @@ rather than from a timer alone; `--int1-after` supplies one. sequence still stops, the cross-build confirmation of the latch driver, and every option switch. +## ISDN Courier XMP images + +`Ie030002.xmp` is an ISDN Courier update payload, and it is a different animal +from an XMF: no product text header, and an obfuscated body. + +```sh +python3 -m courier_emu xmp-info Ie030002.xmp +python3 -m courier_emu extract Ie030002.xmp extracted/Ie030002 +``` + +| File range | Contents | +|---|---| +| `0x00000..0x0007f` | 128-byte header: `USR XMP\0` magic, three small fields, and a 0x70-byte table | +| `0x00080..0xb807f` | 0xb8000-byte payload, every byte XOR `0x45` | + +The key falls out of the image without any code analysis. Erased flash still +dominates the payload, and the pad byte reads `0xba`; `0xff ^ 0xba` is `0x45`. +Decoding with it turns `0xff` back into the most common byte, and the result +carries the VRTX kernel banner (`Copyright 1988, Ready Systems`) and the ISDN +rate-adaptation strings (`SET_V110_ENTRY`, `V110_ATO`). + +The payload decodes to three programmed spans, the last being a two-byte word at +the very top of flash: + +| Payload range | Size | +|---|---| +| `0x00000..0x5d320` | 381,728 | +| `0x64000..0xaab0c` | 289,548 | +| `0xb7ffe..0xb8000` | 2 | + +It is an 80386 image, and it says so at payload offset `0x38`, where it clears +`dr0..dr3` and `dr7` — registers the 80186 supervisor does not have. The code +around it programs a linear address into `dr0`, sets the local and global enable +bits in `dr7`, and installs its own INT1 (`#DB`) handler at `4000:0148`, so the +firmware drives hardware breakpoints as a normal runtime mechanism. Note that +this is vector 1, distinct from the 80186's `INT1_VECTOR = 13` pin interrupt in +`timers.py`. + +Nothing here executes yet. What is loaded is the container and the decoded body; +what is not modelled is the board. Two things stand out from the decode: + +- Debug registers. Unicorn does not deliver `#DB` from guest-programmed `dr0..3`, + so the harness would have to match breakpoints itself. +- The 0x70-byte header table at offset `0x10` is plaintext, not obfuscated, and + plainly structured — a handful of 16-bit values recur through it — but its + layout is not recovered, so `xmp-info` reports it verbatim as + `header_table_undecoded` rather than inventing fields for it. + +The load base is a modelling choice, as it is for an XMF. `FLASH_PHYSICAL_BASE` +is set to `0x40000` because the boot code installs its INT1 handler in segment +`0x4000`; the header's `load_hint` field reads `0x40`, which is consistent with +that base in 4 KiB units, but nothing in the image confirms the unit. + +No protected-mode entry appears in the decoded payload — no `lgdt`, `lidt`, +`lmsw`, or `mov cr` anywhere in it. This is 386 code running in real mode, using +32-bit registers, `0x66`/`0x67` prefixes, and the debug registers. + +## ISDN Courier NAC images + +`Ie030002.nac` is the same firmware in a different container, and it is not +obfuscated at all. It is **Intel HEX with the ASCII stripped out**: each record +is a length byte, a big-endian 16-bit address, a type byte, and that many data +bytes. The big-endian address is the giveaway — everything else in these images +is little-endian, but Intel HEX writes its address big-endian even on x86. + +```sh +python3 -m courier_emu nac-info Ie030002.nac +python3 -m courier_emu extract Ie030002.nac extracted/Ie030002 +``` + +| File range | Contents | +|---|---| +| `0x00000..0x0001f` | 32-byte header | +| `0x00020..0xcd1a6` | Binary Intel HEX record stream | +| `0xcd1a7..0xcd1a8` | Two trailing bytes, `e4 a0` | + +Header fields: + +| Offset | Contents | +|---|---| +| `0x03` | `u32` record-stream length — exactly file size minus header minus trailer | +| `0x08` | Version triple `03 00 02`, matching the `Ie030002` file name: 3.0.2 | +| `0x0f` | Product tag `IE(`, the same tag the `.sdl` loader carries | + +The record types are the Intel HEX ones: + +| Type | Count | Meaning | +|---|---:|---| +| `0x00` | 42,023 | Data | +| `0x02` | 197 | Extended segment address, big-endian, scaled by 16 | +| `0x03` | 1 | Start segment address, `0ce0:0000` | +| `0x01` | 1 | End of file | + +Unlike ASCII Intel HEX there is no per-record checksum byte; parsing without one +consumes the stream exactly, from the end of the header to the EOF record. + +The stream's very first record is a type `0x02` setting segment `0x4000`, so the +image places itself at physical `0x40000` — the harness does not have to assume a +base for a NAC the way it does for an XMF. That independently confirms the base +the XMP section above had to infer from the boot code's INT1 handler. + +The two containers agree exactly. Flattening the NAC's 42,023 data records +produces a `0xb8000` image at `0x40000` that is byte-for-byte identical to the +XOR-decoded XMP payload, and the 82,879 bytes the NAC never paints are precisely +the bytes that read as erased flash in the XMP. Two independently encoded +containers reaching the same image is the strongest check available on both +decodes, and `tests/test_nac.py` asserts it. + +What is not recovered: the two trailing bytes `e4 a0`. They are not a byte sum of +the record stream and match none of the common CRC-16s (CCITT-FALSE, XMODEM, ARC, +MODBUS, KERMIT, GENIBUS) over either the stream or the whole file, so `nac-info` +reports them verbatim as `trailer_undecoded`. + +The start segment address `0ce0:0000` is physical `0xce00`, which is RAM well +below the flash — the entry after the boot block relocates itself, consistent +with the code at payload `0x300` loading `0x0ce0` into a segment register. + ## Board latches, front panel, and NVRAM Every board output goes through one read-modify-write latch driver, recovered at diff --git a/courier_emu/cli.py b/courier_emu/cli.py index 2748b64..898b53a 100644 --- a/courier_emu/cli.py +++ b/courier_emu/cli.py @@ -20,8 +20,10 @@ from .panel import ( USABLE_BOARD_IDS, ) from .images import load_image +from .nac import NacFormatError, NacImage from .rom import CourierRom, RomFormatError from .xmf import XmfFormatError, XmfImage +from .xmp import XmpFormatError, XmpImage DEFAULT_LINE_SOCKET = "/tmp/courier-line.sock" from .dsp import run_dsp @@ -242,7 +244,22 @@ def build_parser() -> argparse.ArgumentParser: ) rom_info.add_argument("image") - extract = subparsers.add_parser("extract", help="split the header, DSP, and supervisor") + xmp_info = subparsers.add_parser( + "xmp-info", + help="validate and describe an obfuscated ISDN Courier XMP image", + ) + xmp_info.add_argument("image") + + nac_info = subparsers.add_parser( + "nac-info", + help="validate and describe an ISDN Courier NAC record stream", + ) + nac_info.add_argument("image") + + extract = subparsers.add_parser( + "extract", + help="split an XMF into header, DSP, and supervisor, or unpack an XMP or NAC", + ) extract.add_argument("image") extract.add_argument("directory") @@ -502,9 +519,21 @@ def main(argv: list[str] | None = None) -> int: if args.command == "rom-info": _print_json(CourierRom.load(args.image).describe()) return 0 + if args.command == "xmp-info": + _print_json(XmpImage.load(args.image).describe()) + return 0 + if args.command == "nac-info": + _print_json(NacImage.load(args.image).describe()) + return 0 if args.command == "extract": - image = XmfImage.load(args.image) - paths = image.extract(args.directory) + try: + source: XmfImage | XmpImage | NacImage = XmfImage.load(args.image) + except XmfFormatError: + try: + source = XmpImage.load(args.image) + except XmpFormatError: + source = NacImage.load(args.image) + paths = source.extract(args.directory) _print_json({"files": [str(path.resolve()) for path in paths]}) return 0 if args.command == "run": @@ -544,6 +573,14 @@ def main(argv: list[str] | None = None) -> int: ) ) return 0 - except (OSError, XmfFormatError, RomFormatError, ValueError, json.JSONDecodeError) as exc: + except ( + OSError, + XmfFormatError, + RomFormatError, + XmpFormatError, + NacFormatError, + ValueError, + json.JSONDecodeError, + ) as exc: parser.error(str(exc)) return 1 diff --git a/courier_emu/images.py b/courier_emu/images.py index 2657986..9040fe1 100644 --- a/courier_emu/images.py +++ b/courier_emu/images.py @@ -2,16 +2,19 @@ from __future__ import annotations from pathlib import Path +from .nac import NacFormatError, NacImage from .rom import CourierRom, RomFormatError from .xmf import XmfFormatError, XmfImage +from .xmp import XmpFormatError, XmpImage -def load_image(path: str | Path) -> XmfImage | CourierRom: - """Load either an XMF update payload or a complete flash ROM. +def load_image(path: str | Path) -> XmfImage | CourierRom | XmpImage | NacImage: + """Load an XMF payload, a flash ROM, or an ISDN XMP or NAC. - The two are told apart by their own contents rather than by extension: an - XMF starts with the Courier text header, and a ROM ends with the 80186 - reset vector. + They are told apart by their own contents rather than by extension: an XMF + starts with the Courier text header, a ROM ends with the 80186 reset vector, + an XMP starts with its own magic and carries an obfuscated body, and a NAC + declares its record-stream length in its header. """ try: return XmfImage.load(path) @@ -19,7 +22,13 @@ def load_image(path: str | Path) -> XmfImage | CourierRom: try: return CourierRom.load(path) except RomFormatError as rom_error: - raise XmfFormatError( - f"{Path(path).name} is neither a Courier XMF ({xmf_error}) " - f"nor a Courier ROM ({rom_error})" - ) from rom_error + try: + return XmpImage.load(path) + except XmpFormatError as xmp_error: + try: + return NacImage.load(path) + except NacFormatError as nac_error: + raise XmfFormatError( + f"{Path(path).name} is not a Courier XMF ({xmf_error}), " + f"ROM ({rom_error}), XMP ({xmp_error}), or NAC ({nac_error})" + ) from nac_error diff --git a/courier_emu/nac.py b/courier_emu/nac.py new file mode 100644 index 0000000..96456f2 --- /dev/null +++ b/courier_emu/nac.py @@ -0,0 +1,268 @@ +from __future__ import annotations + +from dataclasses import dataclass +from hashlib import sha256 +from pathlib import Path +import struct + + +# A NAC is the ISDN Courier's other update container. Its record stream is +# Intel HEX with the ASCII stripped out: each record is a length byte, a +# big-endian 16-bit address, a type byte, and that many data bytes. The +# big-endian address is the giveaway -- everything else in these images is +# little-endian, and Intel HEX writes its address big-endian even on x86. +# +# Unlike ASCII Intel HEX there is no per-record checksum byte. Parsing without +# one consumes this image exactly, from the end of the header to the EOF record. +HEADER_SIZE = 0x20 +TRAILER_SIZE = 2 + +# Header fields. The version triple matches the file name: Ie030002 is 3.0.2. +VERSION_OFFSET = 0x08 +PRODUCT_OFFSET = 0x0F +PRODUCT_SIZE = 3 +STREAM_LENGTH_OFFSET = 0x03 + +RECORD_DATA = 0x00 +RECORD_EOF = 0x01 +RECORD_EXTENDED_SEGMENT = 0x02 +RECORD_START_SEGMENT = 0x03 + +MAX_RECORD_DATA = 0x10 + +# The stream opens by setting segment 0x4000, so the image places itself at +# physical 0x40000 rather than the harness having to assume a base. That is the +# same base the XMP payload decodes at, and the same one the boot code uses when +# it installs its INT1 handler in segment 0x4000. +ERASED_BYTE = 0xFF + + +class NacFormatError(ValueError): + """Raised when a file does not match the recovered Courier NAC layout.""" + + +@dataclass(frozen=True) +class NacRecord: + """One binary Intel HEX record.""" + + file_offset: int + kind: int + address: int + data: bytes + + @property + def length(self) -> int: + return len(self.data) + + +@dataclass(frozen=True) +class NacImage: + """A binary Intel HEX update stream and the flash image it paints.""" + + path: Path + data: bytes + records: tuple[NacRecord, ...] + spans: tuple[tuple[int, bytes], ...] + start_segment: int | None + start_offset: int | None + + @classmethod + def load(cls, path: str | Path) -> "NacImage": + source = Path(path) + data = source.read_bytes() + if len(data) < HEADER_SIZE + TRAILER_SIZE: + raise NacFormatError(f"file is too short to be a Courier NAC ({len(data):#x} bytes)") + declared = struct.unpack_from(" byte, painted in record order so that a later + # record overwrites an earlier one at the same address, as a loader + # walking the stream would. + painted: dict[int, int] = {} + segment: int | None = None + start: tuple[int, int] | None = None + offset = HEADER_SIZE + limit = len(data) - TRAILER_SIZE + seen_eof = False + while offset < limit: + if offset + 4 > limit: + raise NacFormatError(f"truncated record header at {offset:#x}") + length = data[offset] + address = (data[offset + 1] << 8) | data[offset + 2] + kind = data[offset + 3] + if length > MAX_RECORD_DATA: + raise NacFormatError(f"record at {offset:#x} declares {length:#x} data bytes") + body = data[offset + 4 : offset + 4 + length] + if len(body) != length: + raise NacFormatError(f"truncated record body at {offset:#x}") + records.append(NacRecord(offset, kind, address, body)) + if kind == RECORD_EOF: + seen_eof = True + offset += 4 + length + break + if kind == RECORD_EXTENDED_SEGMENT: + if length != 2: + raise NacFormatError( + f"extended segment record at {offset:#x} carries {length} bytes" + ) + segment = (body[0] << 8) | body[1] + elif kind == RECORD_START_SEGMENT: + if length != 4: + raise NacFormatError( + f"start segment record at {offset:#x} carries {length} bytes" + ) + start = ((body[0] << 8) | body[1], (body[2] << 8) | body[3]) + elif kind == RECORD_DATA: + if segment is None: + raise NacFormatError( + f"data record at {offset:#x} precedes any extended segment record" + ) + base = segment * 16 + address + for index, byte in enumerate(body): + painted[base + index] = byte + else: + raise NacFormatError(f"unknown record type {kind:#04x} at {offset:#x}") + offset += 4 + length + if not seen_eof: + raise NacFormatError("record stream ends without an EOF record") + if offset != limit: + raise NacFormatError( + f"EOF record at {offset:#x} does not end the stream at {limit:#x}" + ) + if not painted: + raise NacFormatError("record stream carries no data records") + + return cls( + source.resolve(), + data, + tuple(records), + _coalesce(painted), + start[0] if start else None, + start[1] if start else None, + ) + + @property + def header(self) -> bytes: + return self.data[:HEADER_SIZE] + + @property + def trailer(self) -> bytes: + """The two bytes after the EOF record. + + Not a byte sum of the stream and not any of the common CRC-16s, so it is + reported verbatim rather than decoded. + """ + return self.data[-TRAILER_SIZE:] + + @property + def digest(self) -> str: + return sha256(self.data).hexdigest() + + @property + def version(self) -> tuple[int, int, int]: + major, minor, patch = self.data[VERSION_OFFSET : VERSION_OFFSET + 3] + return major, minor, patch + + @property + def product(self) -> str: + window = self.data[PRODUCT_OFFSET : PRODUCT_OFFSET + PRODUCT_SIZE] + return window.decode("ascii", "replace") + + @property + def stream_length(self) -> int: + return struct.unpack_from(" int: + return self.spans[0][0] + + @property + def entry_physical(self) -> int | None: + if self.start_segment is None or self.start_offset is None: + return None + return self.start_segment * 16 + self.start_offset + + @property + def data_records(self) -> tuple[NacRecord, ...]: + return tuple(record for record in self.records if record.kind == RECORD_DATA) + + @property + def painted_bytes(self) -> int: + return sum(len(payload) for _, payload in self.spans) + + def flatten(self, fill: int = ERASED_BYTE) -> tuple[int, bytes]: + """Return the base address and one image covering every painted span.""" + base = self.spans[0][0] + end = max(address + len(payload) for address, payload in self.spans) + image = bytearray([fill]) * (end - base) + for address, payload in self.spans: + image[address - base : address - base + len(payload)] = payload + return base, bytes(image) + + def extract(self, directory: str | Path) -> tuple[Path, Path]: + output = Path(directory) + output.mkdir(parents=True, exist_ok=True) + header_path = output / "header.bin" + image_path = output / "int80386.bin" + header_path.write_bytes(self.header) + image_path.write_bytes(self.flatten()[1]) + return header_path, image_path + + def describe(self) -> dict[str, object]: + major, minor, patch = self.version + base, image = self.flatten() + entry = self.entry_physical + return { + "path": str(self.path), + "format": "nac", + "size": len(self.data), + "sha256": self.digest, + "header_size": HEADER_SIZE, + "product": self.product, + "version": f"{major}.{minor}.{patch}", + "stream_length": self.stream_length, + "records": len(self.records), + "data_records": len(self.data_records), + "segment_records": sum( + 1 for record in self.records if record.kind == RECORD_EXTENDED_SEGMENT + ), + "load_base": base, + "flattened_size": len(image), + "painted_bytes": self.painted_bytes, + "spans": [ + {"address": address, "size": len(payload)} for address, payload in self.spans + ], + "start_segment": ( + None + if self.start_segment is None + else f"{self.start_segment:04x}:{self.start_offset:04x}" + ), + "entry_physical": entry, + "trailer_undecoded": self.trailer.hex(), + } + + +def _coalesce(painted: dict[int, int]) -> tuple[tuple[int, bytes], ...]: + """Group painted bytes into contiguous (address, bytes) spans.""" + spans: list[tuple[int, bytes]] = [] + run = bytearray() + start = None + previous = None + for address in sorted(painted): + if previous is not None and address != previous + 1: + spans.append((start, bytes(run))) + run = bytearray() + start = None + if start is None: + start = address + run.append(painted[address]) + previous = address + if start is not None: + spans.append((start, bytes(run))) + return tuple(spans) diff --git a/courier_emu/xmp.py b/courier_emu/xmp.py new file mode 100644 index 0000000..b36e9b5 --- /dev/null +++ b/courier_emu/xmp.py @@ -0,0 +1,204 @@ +from __future__ import annotations + +from dataclasses import dataclass +from hashlib import sha256 +from pathlib import Path +import struct + + +# An XMP is the ISDN Courier's update payload. Unlike an XMF it carries no +# product text header, and its body is obfuscated: every payload byte is XOR'd +# with a single constant. The key is recoverable without any code analysis, +# because erased flash still dominates the image -- the pad byte at the top of +# the payload reads 0xba, and 0xff ^ 0xba is 0x45. +MAGIC = b"USR XMP\x00" +HEADER_SIZE = 0x80 +PAYLOAD_SIZE = 0xB8000 +EXPECTED_SIZE = HEADER_SIZE + PAYLOAD_SIZE +OBFUSCATION_KEY = 0x45 +ERASED_BYTE = 0xFF + +# The payload begins with a far-callable dispatch stub: +# push ds / pusha / mov ax, 000d / mov ds, ax / mov si, 0000 +# mov bx, [si] / shl bx, 1 / cmp bx, 000a / ja short / jmp cs:[bx+001b] +BOOT_SIGNATURE = bytes.fromhex("1e60b80d008ed8be00008b1cd1e383fb") + +# At payload offset 0x38 the firmware clears the 80386 debug registers. This is +# the cheapest positive identification of the 386 image: dr0..dr3 and dr7 do not +# exist on the 80186 supervisor that the XMF pipeline handles. +# xor eax, eax / mov dr0, eax / mov dr1, eax +DEBUG_REGISTER_OFFSET = 0x38 +DEBUG_REGISTER_SIGNATURE = bytes.fromhex("6633c00f23c00f23c8") + +# The boot code installs its INT1 (#DB) handler as 4000:0148, so the payload +# decodes at physical 0x40000, the same flash base the 80186 board uses. Header +# word `load_hint` reads 0x40, which is consistent with that base in 4 KiB +# units, but nothing in the image confirms the unit -- see describe(). +FLASH_PHYSICAL_BASE = 0x40000 + +# A programmed region is separated from the next by at least this much erased +# flash. Smaller 0xff runs occur inside ordinary code and tables. +REGION_GAP = 0x400 + + +class XmpFormatError(ValueError): + """Raised when a file does not match the recovered Courier XMP layout.""" + + +@dataclass(frozen=True) +class XmpImage: + """An obfuscated ISDN Courier update payload and its decoded body.""" + + path: Path + data: bytes + payload: bytes + + @classmethod + def load(cls, path: str | Path) -> "XmpImage": + source = Path(path) + data = source.read_bytes() + if len(data) != EXPECTED_SIZE: + raise XmpFormatError( + f"expected a {EXPECTED_SIZE:#x}-byte Courier XMP, got {len(data):#x}" + ) + if not data.startswith(MAGIC): + raise XmpFormatError("missing USR XMP magic") + payload = bytes(byte ^ OBFUSCATION_KEY for byte in data[HEADER_SIZE:]) + if not payload.startswith(BOOT_SIGNATURE): + raise XmpFormatError( + f"missing dispatch stub at payload offset 0; " + f"key {OBFUSCATION_KEY:#04x} may be wrong for this image" + ) + window = payload[ + DEBUG_REGISTER_OFFSET : DEBUG_REGISTER_OFFSET + len(DEBUG_REGISTER_SIGNATURE) + ] + if window != DEBUG_REGISTER_SIGNATURE: + raise XmpFormatError( + f"missing 80386 debug-register init at payload offset " + f"{DEBUG_REGISTER_OFFSET:#x}" + ) + return cls(source.resolve(), data, payload) + + @property + def header(self) -> bytes: + return self.data[:HEADER_SIZE] + + @property + def digest(self) -> str: + return sha256(self.data).hexdigest() + + @property + def payload_digest(self) -> str: + return sha256(self.payload).hexdigest() + + @property + def load_base(self) -> int: + return FLASH_PHYSICAL_BASE + + @property + def format_word(self) -> int: + """Header word at 0x08. Reads 0x0f01; its meaning is not recovered.""" + return struct.unpack_from(" int: + """Header word at 0x0a. Reads 0x26b9; not a checksum of the payload.""" + return struct.unpack_from(" int: + """Header dword at 0x0c. Reads 0x40; see FLASH_PHYSICAL_BASE.""" + return struct.unpack_from(" bytes: + """The 0x70 bytes at header offset 0x10. + + Plaintext, not obfuscated, and clearly structured -- a handful of 16-bit + values recur throughout it -- but its layout is not yet recovered, so it + is exposed as raw bytes rather than decoded into fields. + """ + return self.data[0x10:HEADER_SIZE] + + @property + def last_programmed_offset(self) -> int: + index = len(self.payload) - 1 + while index >= 0 and self.payload[index] == ERASED_BYTE: + index -= 1 + return index + + def programmed_regions(self) -> tuple[tuple[int, int], ...]: + """Return (start, end) payload spans separated by erased flash.""" + regions: list[tuple[int, int]] = [] + start: int | None = None + index = 0 + size = len(self.payload) + while index < size: + if self.payload[index] == ERASED_BYTE: + run = index + while run < size and self.payload[run] == ERASED_BYTE: + run += 1 + if run - index >= REGION_GAP: + if start is not None: + regions.append((start, index)) + start = None + index = run + continue + if start is None: + start = index + index = run + continue + if start is None: + start = index + index += 1 + if start is not None: + regions.append((start, size)) + return tuple(regions) + + def file_to_physical(self, payload_offset: int) -> int: + if not 0 <= payload_offset < len(self.payload): + raise ValueError("payload offset outside image") + return FLASH_PHYSICAL_BASE + payload_offset + + def physical_to_file(self, address: int) -> int: + offset = address - FLASH_PHYSICAL_BASE + if not 0 <= offset < len(self.payload): + raise ValueError("physical address is not backed by this image") + return offset + + def extract(self, directory: str | Path) -> tuple[Path, Path]: + output = Path(directory) + output.mkdir(parents=True, exist_ok=True) + header_path = output / "header.bin" + payload_path = output / "int80386.bin" + header_path.write_bytes(self.header) + payload_path.write_bytes(self.payload) + return header_path, payload_path + + def describe(self) -> dict[str, object]: + regions = self.programmed_regions() + return { + "path": str(self.path), + "format": "xmp", + "size": len(self.data), + "sha256": self.digest, + "header_size": HEADER_SIZE, + "obfuscation_key": OBFUSCATION_KEY, + "payload_size": len(self.payload), + "payload_sha256": self.payload_digest, + "format_word": self.format_word, + "header_word": self.header_word, + "load_hint": self.load_hint, + "header_table_undecoded": self.header_table.hex(), + "flash_physical_base": FLASH_PHYSICAL_BASE, + "programmed_regions": [ + { + "start": start, + "end": end, + "size": end - start, + "physical": self.file_to_physical(start), + } + for start, end in regions + ], + "last_programmed_offset": self.last_programmed_offset, + } diff --git a/tests/test_nac.py b/tests/test_nac.py new file mode 100644 index 0000000..77fbaa1 --- /dev/null +++ b/tests/test_nac.py @@ -0,0 +1,192 @@ +from __future__ import annotations + +from pathlib import Path +import struct +import tempfile +import unittest + +from courier_emu.images import load_image +from courier_emu.nac import ( + HEADER_SIZE, + RECORD_DATA, + RECORD_EOF, + RECORD_EXTENDED_SEGMENT, + RECORD_START_SEGMENT, + STREAM_LENGTH_OFFSET, + TRAILER_SIZE, + NacFormatError, + NacImage, +) +from courier_emu.xmf import XmfFormatError +from courier_emu.xmp import XmpImage + + +ROOT = Path(__file__).resolve().parents[1] +IMAGE = ROOT / "Ie030002.nac" +XMP_IMAGE = ROOT / "Ie030002.xmp" +XMF_IMAGE = ROOT / "main211.xmf" + + +@unittest.skipUnless(IMAGE.exists(), "ISDN Courier NAC image is not present") +class NacImageTests(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.image = NacImage.load(IMAGE) + + def test_header_declares_the_record_stream_length(self) -> None: + self.assertEqual( + self.image.stream_length, + len(self.image.data) - HEADER_SIZE - TRAILER_SIZE, + ) + + def test_header_identifies_the_product_and_version(self) -> None: + self.assertEqual(self.image.product, "IE(") + self.assertEqual(self.image.version, (3, 0, 2)) + + def test_the_stream_opens_by_setting_the_flash_segment(self) -> None: + first = self.image.records[0] + self.assertEqual(first.file_offset, HEADER_SIZE) + self.assertEqual(first.kind, RECORD_EXTENDED_SEGMENT) + self.assertEqual(first.data, bytes([0x40, 0x00])) + # Segment 0x4000 puts the image at physical 0x40000, so the base comes + # from the file rather than from an assumption in the harness. + self.assertEqual(self.image.load_base, 0x40000) + + def test_the_stream_ends_with_an_eof_record(self) -> None: + self.assertEqual(self.image.records[-1].kind, RECORD_EOF) + self.assertEqual(self.image.records[-1].data, b"") + + def test_record_kinds_are_limited_to_the_recovered_set(self) -> None: + kinds = {record.kind for record in self.image.records} + self.assertEqual( + kinds, + {RECORD_DATA, RECORD_EOF, RECORD_EXTENDED_SEGMENT, RECORD_START_SEGMENT}, + ) + + def test_data_records_never_exceed_sixteen_bytes(self) -> None: + self.assertTrue(all(record.length <= 0x10 for record in self.image.data_records)) + + def test_start_segment_address(self) -> None: + self.assertEqual(self.image.start_segment, 0x0CE0) + self.assertEqual(self.image.start_offset, 0x0000) + self.assertEqual(self.image.entry_physical, 0xCE00) + + def test_flatten_covers_the_whole_flash_payload(self) -> None: + base, image = self.image.flatten() + self.assertEqual(base, 0x40000) + self.assertEqual(len(image), 0xB8000) + + def test_spans_are_disjoint_and_ordered(self) -> None: + spans = self.image.spans + self.assertTrue(spans) + for (address, payload), (next_address, _) in zip(spans, spans[1:], strict=False): + self.assertLess(address + len(payload), next_address) + self.assertEqual(self.image.painted_bytes, sum(len(p) for _, p in spans)) + + def test_extract_writes_header_and_flattened_image(self) -> None: + with tempfile.TemporaryDirectory() as directory: + header_path, image_path = self.image.extract(directory) + self.assertEqual(header_path.read_bytes(), self.image.header) + self.assertEqual(image_path.read_bytes(), self.image.flatten()[1]) + + def test_load_image_dispatches_to_nac(self) -> None: + self.assertIsInstance(load_image(IMAGE), NacImage) + + def test_describe_reports_the_undecoded_trailer(self) -> None: + described = self.image.describe() + self.assertEqual(described["format"], "nac") + self.assertEqual(described["version"], "3.0.2") + # The two bytes after the EOF record are not a byte sum of the stream + # and match no common CRC-16, so they are reported verbatim. + self.assertEqual(described["trailer_undecoded"], self.image.trailer.hex()) + + +@unittest.skipUnless( + IMAGE.exists() and XMP_IMAGE.exists(), "both ISDN Courier images are needed" +) +class NacAgreesWithXmpTests(unittest.TestCase): + """The NAC and the XMP carry the same firmware in different containers.""" + + @classmethod + def setUpClass(cls) -> None: + cls.nac = NacImage.load(IMAGE) + cls.xmp = XmpImage.load(XMP_IMAGE) + + def test_same_load_base_and_size(self) -> None: + base, image = self.nac.flatten() + self.assertEqual(base, self.xmp.load_base) + self.assertEqual(len(image), len(self.xmp.payload)) + + def test_flattened_images_are_identical(self) -> None: + self.assertEqual(self.nac.flatten()[1], self.xmp.payload) + + def test_every_painted_span_matches_the_xmp_payload(self) -> None: + for address, payload in self.nac.spans: + offset = address - self.xmp.load_base + self.assertEqual(self.xmp.payload[offset : offset + len(payload)], payload) + + def test_unpainted_bytes_are_erased_flash(self) -> None: + _, image = self.nac.flatten() + painted = bytearray(len(image)) + for address, payload in self.nac.spans: + start = address - self.nac.load_base + painted[start : start + len(payload)] = b"\x01" * len(payload) + gaps = [i for i, seen in enumerate(painted) if not seen] + self.assertTrue(gaps) + self.assertTrue(all(self.xmp.payload[i] == 0xFF for i in gaps)) + + +@unittest.skipUnless(IMAGE.exists(), "ISDN Courier NAC image is not present") +class NacRejectionTests(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.data = IMAGE.read_bytes() + + def _load(self, data: bytes) -> NacImage: + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "broken.nac" + path.write_bytes(data) + return NacImage.load(path) + + def test_rejects_a_short_file(self) -> None: + with self.assertRaises(NacFormatError): + self._load(b"\x00" * 8) + + def test_rejects_a_wrong_declared_stream_length(self) -> None: + broken = bytearray(self.data) + struct.pack_into(" int: + return len(self.data) - HEADER_SIZE - TRAILER_SIZE + + def test_rejects_an_unknown_record_type(self) -> None: + broken = bytearray(self.data) + # The first record is the extended segment record at the stream start. + broken[HEADER_SIZE + 3] = 0x7F + with self.assertRaises(NacFormatError): + self._load(bytes(broken)) + + def test_rejects_a_data_record_before_any_segment_record(self) -> None: + broken = bytearray(self.data) + broken[HEADER_SIZE + 3] = RECORD_DATA + with self.assertRaises(NacFormatError): + self._load(bytes(broken)) + + @unittest.skipUnless(XMF_IMAGE.exists(), "XMF image is not present") + def test_an_xmf_is_not_a_nac(self) -> None: + with self.assertRaises(NacFormatError): + NacImage.load(XMF_IMAGE) + + +class LoadImageReportsEveryFormat(unittest.TestCase): + def test_message_names_all_four_containers(self) -> None: + with tempfile.TemporaryDirectory() as directory: + junk = Path(directory) / "junk.bin" + junk.write_bytes(b"not a firmware image") + with self.assertRaises(XmfFormatError) as caught: + load_image(junk) + message = str(caught.exception) + for name in ("XMF", "ROM", "XMP", "NAC"): + self.assertIn(name, message) diff --git a/tests/test_xmp.py b/tests/test_xmp.py new file mode 100644 index 0000000..9fbe040 --- /dev/null +++ b/tests/test_xmp.py @@ -0,0 +1,133 @@ +from __future__ import annotations + +from pathlib import Path +import tempfile +import unittest + +from courier_emu.images import load_image +from courier_emu.xmf import XmfFormatError +from courier_emu.xmp import ( + BOOT_SIGNATURE, + DEBUG_REGISTER_OFFSET, + DEBUG_REGISTER_SIGNATURE, + EXPECTED_SIZE, + FLASH_PHYSICAL_BASE, + HEADER_SIZE, + MAGIC, + OBFUSCATION_KEY, + PAYLOAD_SIZE, + XmpFormatError, + XmpImage, +) + + +ROOT = Path(__file__).resolve().parents[1] +IMAGE = ROOT / "Ie030002.xmp" +XMF_IMAGE = ROOT / "main211.xmf" + + +@unittest.skipUnless(IMAGE.exists(), "ISDN Courier XMP image is not present") +class XmpImageTests(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.image = XmpImage.load(IMAGE) + + def test_container_sizes(self) -> None: + self.assertEqual(len(self.image.data), EXPECTED_SIZE) + self.assertEqual(len(self.image.payload), PAYLOAD_SIZE) + self.assertEqual(HEADER_SIZE + PAYLOAD_SIZE, EXPECTED_SIZE) + self.assertTrue(self.image.data.startswith(MAGIC)) + + def test_payload_is_the_body_xored_with_the_key(self) -> None: + body = self.image.data[HEADER_SIZE:] + expected = bytes(byte ^ OBFUSCATION_KEY for byte in body) + self.assertEqual(self.image.payload, expected) + + def test_decoded_signatures(self) -> None: + self.assertTrue(self.image.payload.startswith(BOOT_SIGNATURE)) + window = self.image.payload[ + DEBUG_REGISTER_OFFSET : DEBUG_REGISTER_OFFSET + len(DEBUG_REGISTER_SIGNATURE) + ] + self.assertEqual(window, DEBUG_REGISTER_SIGNATURE) + + def test_decoding_reaches_the_far_end_of_the_image(self) -> None: + # The VRTX kernel banner and the ISDN rate-adaptation strings sit deep in + # the payload, so finding them proves the key is constant across it. + self.assertIn(b"Copyright 1988, Ready Systems", self.image.payload) + self.assertIn(b"SET_V110_ENTRY", self.image.payload) + + def test_erased_flash_decodes_to_ff(self) -> None: + regions = self.image.programmed_regions() + self.assertGreaterEqual(len(regions), 2) + gap = self.image.payload[regions[0][1] : regions[1][0]] + self.assertTrue(gap) + self.assertEqual(set(gap), {0xFF}) + + def test_address_translation_round_trips(self) -> None: + self.assertEqual(self.image.load_base, FLASH_PHYSICAL_BASE) + self.assertEqual(self.image.file_to_physical(0), FLASH_PHYSICAL_BASE) + self.assertEqual(self.image.physical_to_file(FLASH_PHYSICAL_BASE + 0x100), 0x100) + with self.assertRaises(ValueError): + self.image.physical_to_file(FLASH_PHYSICAL_BASE - 1) + with self.assertRaises(ValueError): + self.image.file_to_physical(PAYLOAD_SIZE) + + def test_extract_writes_header_and_payload(self) -> None: + with tempfile.TemporaryDirectory() as directory: + header_path, payload_path = self.image.extract(directory) + self.assertEqual(header_path.read_bytes(), self.image.header) + self.assertEqual(payload_path.read_bytes(), self.image.payload) + + def test_describe_reports_the_undecoded_header_table(self) -> None: + described = self.image.describe() + self.assertEqual(described["format"], "xmp") + self.assertEqual(described["obfuscation_key"], OBFUSCATION_KEY) + # The 0x70-byte table at header offset 0x10 is not yet reverse + # engineered, so it must be reported verbatim rather than as fields. + self.assertEqual(described["header_table_undecoded"], self.image.header_table.hex()) + + def test_load_image_dispatches_to_xmp(self) -> None: + self.assertIsInstance(load_image(IMAGE), XmpImage) + + def test_rejects_a_wrong_key(self) -> None: + data = bytearray(self.image.data) + data[HEADER_SIZE] ^= 0xFF + with tempfile.TemporaryDirectory() as directory: + broken = Path(directory) / "broken.xmp" + broken.write_bytes(bytes(data)) + with self.assertRaises(XmpFormatError): + XmpImage.load(broken) + + def test_rejects_a_truncated_file(self) -> None: + with tempfile.TemporaryDirectory() as directory: + short = Path(directory) / "short.xmp" + short.write_bytes(self.image.data[: EXPECTED_SIZE - 1]) + with self.assertRaises(XmpFormatError): + XmpImage.load(short) + + def test_rejects_a_missing_magic(self) -> None: + data = bytearray(self.image.data) + data[0] = ord("X") + with tempfile.TemporaryDirectory() as directory: + broken = Path(directory) / "nomagic.xmp" + broken.write_bytes(bytes(data)) + with self.assertRaises(XmpFormatError): + XmpImage.load(broken) + + +class XmpRejectionTests(unittest.TestCase): + @unittest.skipUnless(XMF_IMAGE.exists(), "XMF image is not present") + def test_an_xmf_is_not_an_xmp(self) -> None: + with self.assertRaises(XmpFormatError): + XmpImage.load(XMF_IMAGE) + + def test_load_image_reports_all_three_formats(self) -> None: + with tempfile.TemporaryDirectory() as directory: + junk = Path(directory) / "junk.bin" + junk.write_bytes(b"not a firmware image") + with self.assertRaises(XmfFormatError) as caught: + load_image(junk) + message = str(caught.exception) + self.assertIn("XMF", message) + self.assertIn("ROM", message) + self.assertIn("XMP", message)