From de0a911c9941249a589c482ba6ce5d80bad1445a Mon Sep 17 00:00:00 2001 From: Dmitry Ilyin <6576495+widgetii@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:02:46 +0300 Subject: [PATCH 1/6] Add nanddump + upgrade CLI subcommands nanddump: full NAND backup over the vendor telnet shell -- no UART, no TFTP, no disassembly. Enables the built-in telnet server via DHIP (set_telnet), then reads every raw /dev/mtdNro partition through the shell with 'dd | base64' (ASCII-armored, so the pty cannot corrupt the stream) and verifies each dump against the size declared in /proc/mtd. Targeted at firmwares with a minimal busybox (Zenointel GK7205V510 stock: no gzip/md5sum/tftp/nc), but works on any Linux device exposing /dev/mtd* over telnet. upgrade: CLI wrapper for the existing (hardware-validated) upgrade_firmware() -- flashes a vendor upgrade package (Dahua zzip) over DHIP with progress reporting; --state queries the upgrader. Validated on a Zenointel SD-2N-4G twin (QEMU, stock vendor firmware): telnet enable over DHIP, defcfg partition recovered byte-exact vs the pristine NAND image; a full-dump pass is covered in the PR discussion. --- README.md | 11 +++ dahua/cli.py | 73 +++++++++++++++- dahua/nanddump.py | 216 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 299 insertions(+), 1 deletion(-) create mode 100644 dahua/nanddump.py diff --git a/README.md b/README.md index 0ee1536..9fa80e2 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,13 @@ dhip 10.0.0.10 -u admin -P admin54321 ptz Left --duration 0.5 dhip 10.0.0.10 -u admin -P admin54321 snapshot out.jpg dhip 10.0.0.10 -u admin -P admin54321 events --codes VideoMotion +# enable the vendor telnet shell and back up every raw MTD partition +# over it (no UART/TFTP/NFS needed); needs the camera root shell password +dhip 10.0.0.10 -u admin -P admin54321 nanddump ./backup --shell-pass ivideo + +# flash a vendor upgrade package (Dahua "zzip") -- destructive: needs --confirm +dhip 10.0.0.10 -u admin -P admin54321 upgrade NC-IPTC2200_DL_4G-4_OpenIPC_gk7205v510.bin --confirm + # raw one-shot RPC (backward compatible with the original tool) dhip 10.0.0.10 -u admin -P admin54321 -m magicBox.getSystemInfo dhip 10.0.0.10 -u admin -P admin54321 -m configManager.getConfig --params '{"name":"General"}' @@ -226,6 +233,10 @@ what is reconstructed and covered only by the offline test suite. (`upgrader.prepare` → chunked `appendData` → `execute`) flashed an OpenIPC package onto a GK7205V510 end-to-end and rebooted into it. **Destructive** — requires `confirm=True` and a package built for the exact target. +- Full NAND backup over the vendor telnet shell: `nanddump` (the CLI enables + telnet via DHIP, then reads every raw `/dev/mtdNro` with `dd | base64` and + verifies each size against `/proc/mtd`) reproduced a full 128 MiB vendor + flash byte-exact on a GK7205V510. Root shell account required. **Reconstructed / covered by the offline tests only** diff --git a/dahua/cli.py b/dahua/cli.py index d525638..c038730 100644 --- a/dahua/cli.py +++ b/dahua/cli.py @@ -13,6 +13,8 @@ dhip HOST ptz Left --duration 0.5 dhip HOST snapshot out.jpg dhip HOST events --codes VideoMotion + dhip HOST nanddump ./backup --shell-pass + dhip HOST upgrade coupler.bin --confirm """ from __future__ import annotations @@ -20,6 +22,7 @@ import argparse import json import sys +import time from . import const from .client import DahuaClient @@ -105,6 +108,31 @@ def build_parser() -> argparse.ArgumentParser: p_tel = sub.add_parser("telnet", help="enable/disable the built-in telnet server") p_tel.add_argument("state", nargs="?", choices=("on", "off"), help="omit to read the current state") + + p_nd = sub.add_parser("nanddump", + help="back up every raw MTD partition over the " + "vendor telnet shell (no UART/TFTP needed)") + p_nd.add_argument("output", help="output directory for mtdN-.bin files") + p_nd.add_argument("--telnet-port", type=int, default=23) + p_nd.add_argument("--shell-user", default="root", + help="telnet shell login (camera root account)") + p_nd.add_argument("--shell-pass", default="", + help="telnet shell password (often the same as serial root)") + p_nd.add_argument("--parts", metavar="LIST", + help="comma-separated MTD indices (default: all raw partitions)") + p_nd.add_argument("--no-enable-telnet", action="store_true", + help="do not enable telnet via DHIP first (already enabled)") + + p_up = sub.add_parser("upgrade", + help="flash a vendor upgrade package (Dahua zzip) over DHIP") + p_up.add_argument("package", nargs="?", + help="package file, e.g. the coupler .bin from the releases") + p_up.add_argument("--confirm", action="store_true", + help="acknowledge the brick risk and proceed") + p_up.add_argument("--type", dest="fw_type", default="System", + help="upgrader type parameter (default: System)") + p_up.add_argument("--state", action="store_true", + help="only query the current upgrader state (read-only)") return ap @@ -217,6 +245,48 @@ def main(argv: list[str] | None = None) -> int: else: cam.set_telnet(False) print("[+] telnet disabled", file=sys.stderr) + elif cmd == "nanddump": + from .nanddump import backup + if not args.no_enable_telnet: + cam.set_telnet(True) + print("[+] telnet enabled via DHIP", file=sys.stderr) + parts = ([int(p) for p in args.parts.split(",") if p != ""] + if args.parts else None) + t0 = time.time() + res = backup(args.host, args.output, port=args.telnet_port, + user=args.shell_user, password=args.shell_pass, + parts=parts) + total = sum(r["bytes"] for r in res) + print(f"[+] dumped {len(res)} partitions, {total} bytes " + f"in {time.time() - t0:.0f}s -> {args.output}", + file=sys.stderr) + if not all(r["ok"] for r in res): + print("!! some partitions have a SIZE MISMATCH -- rerun them", + file=sys.stderr) + return 1 + elif cmd == "upgrade": + if args.state or args.package is None: + try: + _print(cam.firmware_state()) + except Exception as exc: # many firmwares lack getState + print(f"[-] upgrader.getState not supported: {exc}", + file=sys.stderr) + if not args.package: + return 0 + if not args.confirm: + print("refusing to flash without --confirm: a wrong package " + "bricks the device. Take an `nanddump` backup first.", + file=sys.stderr) + return 1 + resp = cam.upgrade_firmware( + args.package, confirm=True, fw_type=args.fw_type, + progress=lambda done, total: print( + f"\r[+] upload {done}/{total} bytes", end="", + file=sys.stderr)) + print(file=sys.stderr) + _print(resp) + print("[+] upgrade started; the device writes it out and reboots " + "itself (give it a few minutes)", file=sys.stderr) elif cmd == "events": listener = cam.events(codes=args.codes) print(f"[+] listening for events {args.codes} (Ctrl-C to stop)", @@ -227,7 +297,8 @@ def main(argv: list[str] | None = None) -> int: listener.stop() else: print("nothing to do; pass -m METHOD or a subcommand " - "(info/config/users/ptz/snapshot/events/telnet)", file=sys.stderr) + "(info/config/users/ptz/snapshot/events/telnet/nanddump)", + file=sys.stderr) return 2 return 0 diff --git a/dahua/nanddump.py b/dahua/nanddump.py new file mode 100644 index 0000000..60607e8 --- /dev/null +++ b/dahua/nanddump.py @@ -0,0 +1,216 @@ +"""NAND backup over the vendor telnet shell -- no UART, no TFTP, no NFS. + +Dumps every raw MTD partition of a vendor camera that offers a busybox shell +on telnet (enabled first via ``DahuaClient.set_telnet``). Works with the +minimal applet set found on such firmwares: only ``dd`` and ``base64`` are +used, the telnet stream is ASCII-armored (immune to telnet/pty mangling), +decoded strictly on the host, and every partition is verified against its +declared size from ``/proc/mtd``. + +Designed for Zenointel/XMedia (GK7205) cameras whose stock busybox lacks +gzip/md5sum/tftp, but works on any Linux box exposing /dev/mtd* over telnet. +""" +from __future__ import annotations + +import base64 +import re +import socket +import sys +import time + +IAC, DONT, DO, WONT, WILL = 255, 254, 253, 252, 251 + + +class ShellError(RuntimeError): + pass + + +class TelnetShell: + """Minimal raw telnet client (stdlib sockets; telnetlib is gone in 3.13).""" + + def __init__(self, host: str, port: int = 23, user: str = "root", + password: str = "", login_timeout: int = 15): + self.sock = socket.create_connection((host, port), timeout=10) + self._read_until([b"login:", b"ogin:"], login_timeout) + self._send(user + "\n") + out = self._read_until([b"assword:"], login_timeout) + self._send(password + "\n") + out += self._read_until([b"# ", b"$ ", b"~#", b"/ #"], login_timeout) + if b"incorrect" in out or b"ogin:" in out: + raise ShellError("telnet login failed: " + out.decode(errors="replace")) + # unique marker prefix so echoed command lines never match real output + self.marker = "RZ7Q%d" % (int(time.time()) % 100000) + + def _negotiate(self, data: bytes) -> bytes: + out = bytearray() + i = 0 + while i < len(data): + b = data[i] + if b == IAC and i + 2 < len(data): + cmd, opt = data[i + 1], data[i + 2] + resp = {DO: WONT, DONT: WONT, WILL: DONT, WONT: DONT}.get(cmd) + if resp is not None: + self.sock.sendall(bytes([IAC, resp, opt])) + i += 3 + else: + out.append(b) + i += 1 + return bytes(out) + + def _read_until(self, needles: list[bytes], timeout: int) -> bytes: + buf = bytearray() + end = time.time() + timeout + self.sock.settimeout(0.5) + while time.time() < end: + try: + chunk = self.sock.recv(65536) + except socket.timeout: + if any(n in buf for n in needles): + break + continue + if not chunk: + break + buf += self._negotiate(chunk) + if any(n in buf for n in needles): + break + return bytes(buf) + + def _send(self, text: str) -> None: + self.sock.sendall(text.encode()) + + def run(self, cmd: str, timeout: int = 60) -> tuple[int, str]: + """Run one command, return (rc, output). `timeout` is an IDLE timeout: + the clock resets on every received chunk (streaming-safe).""" + m = self.marker + self._send(f'__m={m}; echo $__m"CMD"; {cmd}; echo $__m"END$?"\n') + buf = bytearray() + end_c = f"{m}END".encode() + cmd_c = f"{m}CMD".encode() + idle = time.time() + timeout + self.sock.settimeout(0.5) + while time.time() < idle: + try: + chunk = self.sock.recv(65536) + except socket.timeout: + if end_c in buf: + break + continue + if not chunk: + break + buf += self._negotiate(chunk) + if end_c in buf: + # the rc digits may straddle a packet boundary -- wait briefly + # for at least one digit to land after the end marker. + tail_start = buf.find(end_c) + len(end_c) + deadline = time.time() + 2 + while time.time() < deadline: + if re.search(rb"\d", bytes(buf[tail_start:])): + break + try: + buf += self._negotiate(self.sock.recv(4096)) + except socket.timeout: + continue + break + idle = time.time() + timeout # got data: reset the idle clock + text = buf.decode(errors="replace") + end_s, cmd_s = f"{m}END", f"{m}CMD" + if end_s not in text: + raise ShellError("timeout while running command: " + cmd[:60]) + head, tail = text.split(end_s, 1) + rc = -1 + digits = re.match(r"\D*(\d+)", tail.replace("\r", "")) + if digits: + rc = int(digits.group(1)) + body = head.split(cmd_s, 1)[1] if cmd_s in head else head + # drop the echoed command line (marker makes it recognizable) + first_nl = body.find("\n") + if first_nl != -1 and m in body[:first_nl + 1]: + body = body[first_nl + 1:] + return rc, body + + def close(self) -> None: + try: + self._send("exit\n") + self.sock.close() + except OSError: + pass + + +MTD_RE = re.compile(r"^mtd(\d+):\s+([0-9a-fA-F]+)\s+([0-9a-fA-F]+)\s+\"([^\"]*)\"") + + +def parse_proc_mtd(text: str) -> list[dict]: + """Return the raw (non-UBI-volume) partitions in table order.""" + parts, raw_erase = [], None + for line in text.splitlines(): + m = MTD_RE.match(line) + if not m: + continue + idx, size, erase, name = int(m.group(1)), int(m.group(2), 16), int(m.group(3), 16), m.group(4) + if raw_erase is None: + raw_erase = erase + if erase != raw_erase: # UBI volume devices (erase 0x1f000 etc.) -- skip + continue + parts.append({"idx": idx, "size": size, "erase": erase, "name": name}) + return parts + + +def dump_partition(shell: TelnetShell, part: dict, out_path: str, + idle_timeout: int = 180) -> tuple[bool, int]: + """dd | base64 one /dev/mtdNro into out_path. Returns (ok, bytes_written).""" + dev = f"/dev/mtd{part['idx']}ro" + cmd = f"dd if={dev} 2>/dev/null | base64" + rc, body = shell.run(cmd, timeout=idle_timeout) + if rc != 0: + raise ShellError(f"dd|base64 on {dev} returned {rc}") + # strip CRs and any echo/prompt noise, keep only the base64 payload lines + payload = [] + for line in body.replace("\r", "").splitlines(): + line = line.strip() + if not line: + continue + if not re.fullmatch(r"[A-Za-z0-9+/]+=*", line): + continue # echo line / prompt -- payload lines are pure base64 + payload.append(line) + data = base64.b64decode("".join(payload), validate=True) + ok = len(data) == part["size"] + with open(out_path, "wb") as f: + f.write(data) + return ok, len(data) + + +def backup(host: str, outdir: str, port: int = 23, user: str = "root", + password: str = "", parts: list[int] | None = None, + verbose: bool = True) -> list[dict]: + """Dump raw MTD partitions over telnet. `parts` selects partition indices; + None = every raw partition (the contiguous vendor map, concat == whole + data-only NAND image).""" + shell = TelnetShell(host, port, user, password) + try: + rc, mtd_text = shell.run("cat /proc/mtd") + if rc != 0 or "mtd" not in mtd_text: + raise ShellError("cannot read /proc/mtd over telnet") + avail = parse_proc_mtd(mtd_text) + if not avail: + raise ShellError("no raw MTD partitions found in /proc/mtd") + todo = [p for p in avail if parts is None or p["idx"] in parts] + if not todo: + raise ShellError("no partition matched -- indices: " + + ",".join(str(p["idx"]) for p in avail)) + import os + os.makedirs(outdir, exist_ok=True) + result = [] + for p in todo: + name = f"mtd{p['idx']}-{p['name']}.bin" + path = f"{outdir}/{name}" + t0 = time.time() + ok, n = dump_partition(shell, p, path) + dt = time.time() - t0 + result.append({**p, "file": path, "ok": ok, "bytes": n}) + if verbose: + state = "OK " if ok else "SIZE MISMATCH" + print(f"[{state}] {path} {n}/{p['size']} bytes " + f"{n / max(dt, 0.001) / 1024:.0f} KiB/s", file=sys.stderr) + return result + finally: + shell.close() From ba66ea49d84f38fc1ba5b0163d161a38d1a57860 Mon Sep 17 00:00:00 2001 From: Dmitry Ilyin <6576495+widgetii@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:23:50 +0300 Subject: [PATCH 2/6] Address review: telnet hygiene, straddle-safe framing, streaming, tests Review findings fixed: 1. 'upgrade --state' is now strictly read-only: supplying a package alongside --state is rejected (exit 2), and the branch returns immediately after the probe. 2. A failed upgrader.getState probe exits non-zero instead of 0. 3. 'nanddump' no longer leaves the root telnet shell enabled: it reads the current InnerServer.Telnet state first, enables telnet only when it was off, and restores it in a finally block -- verified live on the GK7205V510 twin (state off -> dump -> state off again, confirmed via a separate DHIP query). 4. A 'Last login: ...' success banner is no longer mistaken for a repeated login prompt (line-anchored prompt check), and a failed login is detected even when the retry prompt arrives while the client is still waiting for the password prompt. 5. Telnet framing is now a stateful parser: IAC sequences that straddle socket reads are held back instead of leaking into command output, subnegotiation (SB..IAC SE) frames are consumed whole, and escaped 0xff passes through as data. 6. parse_proc_mtd() no longer drops entries by erasesize; it tags UBI volume aliases and skips them only in the automatic dump. An explicit --parts index selects any partition, UBI-mapped or otherwise; a raw partition with an unusual erase size is kept. 7. The dump path streams: payload text goes through an incremental per-line strict-decoding sink straight to disk, so host memory is bounded by the base64 line length, not the partition size (previously several full copies of each partition accumulated). 8. Partition dumps stream into .part and are renamed into place only after the command exit code and the exact byte count check out -- a failed rerun can never truncate a previously complete backup (regression-tested). Adds tests/test_nanddump.py: marker/rc framing across chunk boundaries, negotiation straddle and SB frames, corrupted-payload rejection, /proc/mtd parsing, and an end-to-end fake busybox telnet server exercising login (including the Last login banner and wrong password), byte-exact dumps, atomic replacement and UBI selection. 42 tests pass. Live re-validation on the SD-2N-4G twin (QEMU, stock vendor firmware) with the rewritten code: 'dhip ... nanddump --parts 1' recovered defcfg byte-exact (262144/262144 B vs the pristine flash slice) and restored the telnet state afterwards. --- dahua/cli.py | 66 +++++--- dahua/nanddump.py | 326 +++++++++++++++++++++++++++++----------- tests/test_nanddump.py | 331 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 617 insertions(+), 106 deletions(-) create mode 100644 tests/test_nanddump.py diff --git a/dahua/cli.py b/dahua/cli.py index c038730..af8502c 100644 --- a/dahua/cli.py +++ b/dahua/cli.py @@ -247,32 +247,58 @@ def main(argv: list[str] | None = None) -> int: print("[+] telnet disabled", file=sys.stderr) elif cmd == "nanddump": from .nanddump import backup + # Only touch the device config when needed, and put it back: + # telnet is a root shell -- do not leave it enabled behind us. + was_on = None + enabled_by_us = False + try: + was_on = cam.telnet_enabled() + except Exception: + pass # unreadable state: assume off if not args.no_enable_telnet: - cam.set_telnet(True) - print("[+] telnet enabled via DHIP", file=sys.stderr) - parts = ([int(p) for p in args.parts.split(",") if p != ""] - if args.parts else None) - t0 = time.time() - res = backup(args.host, args.output, port=args.telnet_port, - user=args.shell_user, password=args.shell_pass, - parts=parts) - total = sum(r["bytes"] for r in res) - print(f"[+] dumped {len(res)} partitions, {total} bytes " - f"in {time.time() - t0:.0f}s -> {args.output}", - file=sys.stderr) - if not all(r["ok"] for r in res): - print("!! some partitions have a SIZE MISMATCH -- rerun them", + if not was_on: + cam.set_telnet(True) + enabled_by_us = True + print("[+] telnet enabled via DHIP", file=sys.stderr) + else: + print("[-] telnet already enabled", file=sys.stderr) + try: + parts = ([int(p) for p in args.parts.split(",") if p != ""] + if args.parts else None) + t0 = time.time() + res = backup(args.host, args.output, port=args.telnet_port, + user=args.shell_user, password=args.shell_pass, + parts=parts) + total = sum(r["bytes"] for r in res) + print(f"[+] dumped {len(res)} partitions, {total} bytes " + f"in {time.time() - t0:.0f}s -> {args.output}", file=sys.stderr) - return 1 + finally: + if enabled_by_us: + try: + cam.set_telnet(False) + print("[+] telnet disabled again (was off before)", + file=sys.stderr) + except Exception as exc: + print(f"!! could NOT disable telnet again: {exc}\n" + " Disable it yourself: dhip telnet off", + file=sys.stderr) elif cmd == "upgrade": - if args.state or args.package is None: + if args.state: + if args.package: + print("--state is a read-only probe; drop the package " + "argument to flash", file=sys.stderr) + return 2 try: _print(cam.firmware_state()) - except Exception as exc: # many firmwares lack getState - print(f"[-] upgrader.getState not supported: {exc}", - file=sys.stderr) - if not args.package: return 0 + except Exception as exc: # many firmwares lack getState + print(f"[-] upgrader.getState failed: {exc}", file=sys.stderr) + return 1 + if args.package is None: + print("nothing to do: pass a package (with --confirm) or " + "--state", file=sys.stderr) + return 2 if not args.confirm: print("refusing to flash without --confirm: a wrong package " "bricks the device. Take an `nanddump` backup first.", diff --git a/dahua/nanddump.py b/dahua/nanddump.py index 60607e8..b69c575 100644 --- a/dahua/nanddump.py +++ b/dahua/nanddump.py @@ -3,9 +3,9 @@ Dumps every raw MTD partition of a vendor camera that offers a busybox shell on telnet (enabled first via ``DahuaClient.set_telnet``). Works with the minimal applet set found on such firmwares: only ``dd`` and ``base64`` are -used, the telnet stream is ASCII-armored (immune to telnet/pty mangling), -decoded strictly on the host, and every partition is verified against its -declared size from ``/proc/mtd``. +used, the stream is ASCII-armored (immune to telnet/pty mangling), decoded +strictly on the host, and every partition is verified against its declared +size from ``/proc/mtd`` before it replaces anything on disk. Designed for Zenointel/XMedia (GK7205) cameras whose stock busybox lacks gzip/md5sum/tftp, but works on any Linux box exposing /dev/mtd* over telnet. @@ -13,12 +13,13 @@ from __future__ import annotations import base64 +import os import re import socket import sys import time -IAC, DONT, DO, WONT, WILL = 255, 254, 253, 252, 251 +IAC, DONT, DO, WONT, WILL, SB, SE = 255, 254, 253, 252, 251, 250, 240 class ShellError(RuntimeError): @@ -26,35 +27,79 @@ class ShellError(RuntimeError): class TelnetShell: - """Minimal raw telnet client (stdlib sockets; telnetlib is gone in 3.13).""" + """Minimal raw telnet client (stdlib sockets; telnetlib is gone in 3.13). + + Keeps telnet parser state across socket reads, so a negotiation sequence + split between two ``recv`` calls can never leak into command output. + """ def __init__(self, host: str, port: int = 23, user: str = "root", password: str = "", login_timeout: int = 15): self.sock = socket.create_connection((host, port), timeout=10) - self._read_until([b"login:", b"ogin:"], login_timeout) - self._send(user + "\n") - out = self._read_until([b"assword:"], login_timeout) - self._send(password + "\n") - out += self._read_until([b"# ", b"$ ", b"~#", b"/ #"], login_timeout) - if b"incorrect" in out or b"ogin:" in out: - raise ShellError("telnet login failed: " + out.decode(errors="replace")) + try: + self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + except OSError: + pass + self._carry = b"" + try: + self._read_until([b"login:", b"ogin:"], login_timeout) + self._send(user + "\n") + # a failed login usually bounces back to a fresh "login:" prompt + # while we are still waiting for the password prompt, so keep + # everything since the username went out and check it all. + mid = self._read_until([b"assword:", b"login:"], login_timeout) + self._send(password + "\n") + out = mid + self._read_until([b"# ", b"$ ", b"~#", b"/ #"], + login_timeout) + # A repeated prompt is a line consisting of (l)ogin: alone; a + # success banner such as "Last login: Sun Nov 22 ..." has text + # after the colon and must NOT be taken for a login failure. + text = out.decode(errors="replace") + if "incorrect" in text.lower() or re.search(r"(?im)^\s*o?login:?\s*$", text): + raise ShellError("telnet login failed: " + text.strip()[-200:]) + except ShellError: + self.close() + raise # unique marker prefix so echoed command lines never match real output self.marker = "RZ7Q%d" % (int(time.time()) % 100000) + # -- telnet wire ---------------------------------------------------------------- def _negotiate(self, data: bytes) -> bytes: + """Strip telnet control sequences; keep partial ones for the next read.""" + data = self._carry + data + self._carry = b"" out = bytearray() - i = 0 - while i < len(data): + i, n = 0, len(data) + while i < n: b = data[i] - if b == IAC and i + 2 < len(data): - cmd, opt = data[i + 1], data[i + 2] + if b != IAC: + out.append(b) + i += 1 + continue + if i + 1 >= n: # IAC alone: wait for more + self._carry = data[i:] + break + cmd = data[i + 1] + if cmd == IAC: # escaped 0xff + out.append(IAC) + i += 2 + elif cmd in (DO, DONT, WILL, WONT): # 3-byte option nego + if i + 2 >= n: + self._carry = data[i:] + break + opt = data[i + 2] resp = {DO: WONT, DONT: WONT, WILL: DONT, WONT: DONT}.get(cmd) if resp is not None: self.sock.sendall(bytes([IAC, resp, opt])) i += 3 - else: - out.append(b) - i += 1 + elif cmd == SB: # subnegotiation: skip to IAC SE + end = data.find(bytes([IAC, SE]), i + 2) + if end == -1: + self._carry = data[i:] + break + i = end + 2 + else: # unsupported 2-byte command + i += 2 return bytes(out) def _read_until(self, needles: list[bytes], timeout: int) -> bytes: @@ -65,68 +110,60 @@ def _read_until(self, needles: list[bytes], timeout: int) -> bytes: try: chunk = self.sock.recv(65536) except socket.timeout: - if any(n in buf for n in needles): + if any(nd in buf for nd in needles): break continue if not chunk: break buf += self._negotiate(chunk) - if any(n in buf for n in needles): + if any(nd in buf for nd in needles): break return bytes(buf) def _send(self, text: str) -> None: self.sock.sendall(text.encode()) + # -- command protocol ------------------------------------------------------------- def run(self, cmd: str, timeout: int = 60) -> tuple[int, str]: """Run one command, return (rc, output). `timeout` is an IDLE timeout: the clock resets on every received chunk (streaming-safe).""" + chunks: list[str] = [] + rc = self.run_stream(cmd, _ListSink(chunks), timeout=timeout) + return rc, "".join(chunks) + + def run_stream(self, cmd: str, sink, timeout: int = 60) -> int: + """Run one command, feeding payload text to `sink.feed()` as it + arrives (memory bounded by the consumer, not the command output). + Returns the command's exit code, or -1 if it could not be read.""" m = self.marker self._send(f'__m={m}; echo $__m"CMD"; {cmd}; echo $__m"END$?"\n') - buf = bytearray() - end_c = f"{m}END".encode() - cmd_c = f"{m}CMD".encode() + split = _MarkerSplit(m) idle = time.time() + timeout self.sock.settimeout(0.5) while time.time() < idle: try: chunk = self.sock.recv(65536) except socket.timeout: - if end_c in buf: + if split.finished: break continue if not chunk: break - buf += self._negotiate(chunk) - if end_c in buf: - # the rc digits may straddle a packet boundary -- wait briefly - # for at least one digit to land after the end marker. - tail_start = buf.find(end_c) + len(end_c) - deadline = time.time() + 2 - while time.time() < deadline: - if re.search(rb"\d", bytes(buf[tail_start:])): - break + payload = split.feed(self._negotiate(chunk).decode(errors="replace")) + if payload: + sink.feed(payload) + if split.finished: + # rc digits may straddle packets: drain briefly for them + rc_deadline = time.time() + 2 + while time.time() < rc_deadline and not split.rc_digits(): try: - buf += self._negotiate(self.sock.recv(4096)) + split.feed(self._negotiate(self.sock.recv(4096)) + .decode(errors="replace")) except socket.timeout: - continue + pass break idle = time.time() + timeout # got data: reset the idle clock - text = buf.decode(errors="replace") - end_s, cmd_s = f"{m}END", f"{m}CMD" - if end_s not in text: - raise ShellError("timeout while running command: " + cmd[:60]) - head, tail = text.split(end_s, 1) - rc = -1 - digits = re.match(r"\D*(\d+)", tail.replace("\r", "")) - if digits: - rc = int(digits.group(1)) - body = head.split(cmd_s, 1)[1] if cmd_s in head else head - # drop the echoed command line (marker makes it recognizable) - first_nl = body.find("\n") - if first_nl != -1 and m in body[:first_nl + 1]: - body = body[first_nl + 1:] - return rc, body + return split.rc_digits()[1] if split.rc_digits() else -1 def close(self) -> None: try: @@ -136,55 +173,174 @@ def close(self) -> None: pass +class _ListSink: + def __init__(self, chunks: list[str]): + self.chunks = chunks + + def feed(self, text: str) -> None: + self.chunks.append(text) + + +class _MarkerSplit: + """Split a marker-framed stream into (payload, rc). + + States: wait for the expanded ``CMD`` output line, then emit + everything as payload until ``END`` appears; hold back the tail of + every chunk so a marker cut across socket reads cannot slip into the + payload. After END, subsequent text (the ``$?`` digits) accumulates into + ``rc_text``. + """ + + def __init__(self, marker: str): + self.cmd_s, self.end_s = marker + "CMD", marker + "END" + self._carry = "" + self.state = 0 # 0 = waiting for CMD, 1 = payload, 2 = after END + self.rc_text = "" + self.finished = False + + def feed(self, text: str) -> str: + if self.state == 0: + text = self._carry + text + i = text.find(self.cmd_s) + if i == -1: + # everything before the CMD marker is the echoed command line; + # keep only the tail that could still start the marker + hold = len(self.cmd_s) - 1 + self._carry = text[-hold:] if len(text) > hold else text + return "" + text = text[i + len(self.cmd_s):] + self._carry = "" + self.state = 1 + if self.state == 1: + text = self._carry + text + self._carry = "" + i = text.find(self.end_s) + if i == -1: + hold = len(self.end_s) - 1 + if len(text) <= hold: + self._carry = text + return "" + self._carry, emit = text[-hold:], text[:-hold] + return emit + self.rc_text = text[i + len(self.end_s):] + self.state = 2 + self.finished = True + return text[:i] + self.rc_text += text # state 2: draining the exit-code digits + return "" + + def rc_digits(self) -> tuple[int, int] | None: + m = re.match(r"\s*\D{0,3}(\d{1,3})", self.rc_text) + return (0, int(m.group(1))) if m else None + + +class _Base64FileSink: + """Incremental strict decoder for `dd | base64` output. + + Writes decoded bytes straight to a file, one base64 line at a time + (memory bounded by the line length, not the partition size). Lines that + are not pure base64 -- the echoed command, shell prompts -- are dropped; + a genuinely corrupt line fails the strict decode and aborts the dump + loudly rather than silently producing a short file. + """ + + LINE = re.compile(r"[A-Za-z0-9+/]+=*") + + def __init__(self, path: str): + self.fh = open(path, "wb") + self.partial = "" + self.n = 0 + + def feed(self, text: str) -> None: + self.partial += text.replace("\r", "") + while "\n" in self.partial: + line, self.partial = self.partial.split("\n", 1) + self._decode(line.strip()) + + def _decode(self, line: str) -> None: + if not line or not self.LINE.fullmatch(line): + return # echo line / prompt noise, not payload + data = base64.b64decode(line, validate=True) + self.fh.write(data) + self.n += len(data) + + def finish(self) -> int: + """Flush the final (unterminated) line, close; return bytes written.""" + try: + self._decode(self.partial.strip()) + finally: + self.fh.close() + return self.n + + def abort(self) -> None: + self.fh.close() + + MTD_RE = re.compile(r"^mtd(\d+):\s+([0-9a-fA-F]+)\s+([0-9a-fA-F]+)\s+\"([^\"]*)\"") def parse_proc_mtd(text: str) -> list[dict]: - """Return the raw (non-UBI-volume) partitions in table order.""" + """Parse every /proc/mtd entry in table order. + + Entries whose erasesize is smaller than the raw-device erasesize are UBI + volume mappings (e.g. 0x1f000 next to the raw 0x20000 on GK7205): they + alias data already covered by the raw partitions and are tagged + ``ubi=True`` so the automatic dump skips them. Explicit ``parts`` indices + still select them, and a raw partition with an unusual erase size is kept + (tagged, not dropped) -- only the automatic heuristic skips UBI volumes. + """ parts, raw_erase = [], None for line in text.splitlines(): m = MTD_RE.match(line) if not m: continue - idx, size, erase, name = int(m.group(1)), int(m.group(2), 16), int(m.group(3), 16), m.group(4) + idx, size, erase = int(m.group(1)), int(m.group(2), 16), int(m.group(3), 16) if raw_erase is None: raw_erase = erase - if erase != raw_erase: # UBI volume devices (erase 0x1f000 etc.) -- skip - continue - parts.append({"idx": idx, "size": size, "erase": erase, "name": name}) + parts.append({"idx": idx, "size": size, "erase": erase, + "name": m.group(4), "ubi": erase != raw_erase}) return parts def dump_partition(shell: TelnetShell, part: dict, out_path: str, idle_timeout: int = 180) -> tuple[bool, int]: - """dd | base64 one /dev/mtdNro into out_path. Returns (ok, bytes_written).""" + """dd | base64 one /dev/mtdNro into out_path. Returns (ok, bytes_written). + + Streams into ``out_path + ".part"`` and atomically replaces ``out_path`` + only after the command completed and the byte count matches the partition + size, so a failed rerun can never truncate a previously complete backup. + """ dev = f"/dev/mtd{part['idx']}ro" - cmd = f"dd if={dev} 2>/dev/null | base64" - rc, body = shell.run(cmd, timeout=idle_timeout) + tmp_path = out_path + ".part" + sink = _Base64FileSink(tmp_path) + rc = shell.run_stream(f"dd if={dev} 2>/dev/null | base64", sink, + timeout=idle_timeout) + try: + n = sink.finish() + except Exception: + sink.abort() + os.unlink(tmp_path) + raise if rc != 0: - raise ShellError(f"dd|base64 on {dev} returned {rc}") - # strip CRs and any echo/prompt noise, keep only the base64 payload lines - payload = [] - for line in body.replace("\r", "").splitlines(): - line = line.strip() - if not line: - continue - if not re.fullmatch(r"[A-Za-z0-9+/]+=*", line): - continue # echo line / prompt -- payload lines are pure base64 - payload.append(line) - data = base64.b64decode("".join(payload), validate=True) - ok = len(data) == part["size"] - with open(out_path, "wb") as f: - f.write(data) - return ok, len(data) + os.unlink(tmp_path) + raise ShellError(f"dd|base64 on {dev} failed (rc={rc})") + if n != part["size"]: + os.unlink(tmp_path) + raise ShellError(f"{dev}: expected {part['size']} bytes, got {n}") + os.replace(tmp_path, out_path) + return True, n def backup(host: str, outdir: str, port: int = 23, user: str = "root", password: str = "", parts: list[int] | None = None, verbose: bool = True) -> list[dict]: - """Dump raw MTD partitions over telnet. `parts` selects partition indices; - None = every raw partition (the contiguous vendor map, concat == whole - data-only NAND image).""" + """Dump raw MTD partitions over telnet into ``outdir``. + + ``parts=None`` dumps every raw partition in table order (skipping UBI + volume aliases); explicit indices select any partition, including + UBI-mapped ones. Raises ``ShellError`` on any failed or size-mismatched + partition: a partial result file never replaces a good one. + """ shell = TelnetShell(host, port, user, password) try: rc, mtd_text = shell.run("cat /proc/mtd") @@ -192,24 +348,22 @@ def backup(host: str, outdir: str, port: int = 23, user: str = "root", raise ShellError("cannot read /proc/mtd over telnet") avail = parse_proc_mtd(mtd_text) if not avail: - raise ShellError("no raw MTD partitions found in /proc/mtd") - todo = [p for p in avail if parts is None or p["idx"] in parts] + raise ShellError("no MTD partitions found in /proc/mtd") + todo = ([p for p in avail if p["idx"] in parts] if parts is not None + else [p for p in avail if not p["ubi"]]) if not todo: raise ShellError("no partition matched -- indices: " + ",".join(str(p["idx"]) for p in avail)) - import os os.makedirs(outdir, exist_ok=True) result = [] for p in todo: - name = f"mtd{p['idx']}-{p['name']}.bin" - path = f"{outdir}/{name}" + path = f"{outdir}/mtd{p['idx']}-{p['name']}.bin" t0 = time.time() - ok, n = dump_partition(shell, p, path) + _, n = dump_partition(shell, p, path) dt = time.time() - t0 - result.append({**p, "file": path, "ok": ok, "bytes": n}) + result.append({**p, "file": path, "ok": True, "bytes": n}) if verbose: - state = "OK " if ok else "SIZE MISMATCH" - print(f"[{state}] {path} {n}/{p['size']} bytes " + print(f"[OK ] {path} {n}/{p['size']} bytes " f"{n / max(dt, 0.001) / 1024:.0f} KiB/s", file=sys.stderr) return result finally: diff --git a/tests/test_nanddump.py b/tests/test_nanddump.py new file mode 100644 index 0000000..55bf183 --- /dev/null +++ b/tests/test_nanddump.py @@ -0,0 +1,331 @@ +"""Offline tests for dahua.nanddump: telnet framing, marker/rc handling, +base64 stream decoding, /proc/mtd parsing, and a fake busybox end-to-end. + +The fake server speaks just enough of a busybox telnet session to exercise +the real client: login prompt(s), an optional "Last login: ..." banner, +marker-framed commands with `dd | base64` payloads, and Telnet control +sequences deliberately split across writes. +""" +import base64 +import os +import re +import socket +import tempfile +import threading + +import pytest + +from dahua.nanddump import ( + TelnetShell, ShellError, _MarkerSplit, _Base64FileSink, parse_proc_mtd, + dump_partition, backup, +) + +MTD_TEXT = """dev: size erasesize name +mtd0: 00200000 00020000 "boot" +mtd1: 00040000 00020000 "defcfg" +mtd2: 003c0000 00020000 "kernel" +mtd3: 02a00000 00020000 "root" +mtd4: 01000000 00020000 "custom" +mtd5: 00c00000 00020000 "config" +mtd6: 02600000 00020000 "database" +mtd7: 00800000 00020000 "appdata1" +mtd8: 00300000 00020000 "appdata2" +mtd9: 00300000 00020000 "encrypt" +mtd10: 01b20000 0001f000 "rootfs" +mtd11: 00c1c000 0001f000 "custom" +mtd12: 00ae6000 0001f000 "config" +""" + +SMALL_MTD = """dev: size erasesize name +mtd0: 00000004 00020000 "boot" +mtd1: 00000010 00020000 "defcfg" +mtd2: 00001000 00020000 "kernel" +mtd10: 00000020 0001f000 "rootfs" +mtd11: 00000020 0001f000 "custom" +mtd12: 00000020 0001f000 "config" +""" + +IAC_CTRL = re.compile(rb"\xff[\xfa-\xfe].") + + +# -- parsers ------------------------------------------------------------------- + +def test_parse_proc_mtd_tags_ubi_volumes(): + parts = parse_proc_mtd(MTD_TEXT) + assert [p["idx"] for p in parts] == list(range(13)) + assert [p["idx"] for p in parts if p["ubi"]] == [10, 11, 12] + assert parts[3]["size"] == 0x2A00000 + assert [p["idx"] for p in parts if not p["ubi"]] == list(range(10)) + + +def test_marker_split_normal_and_rc(): + m = _MarkerSplit("MK") + emit = m.feed("noise\r\nMKCMD\n") + m.feed("PAYLOAD\nMK") + m.feed("END0\r\n/ # ") + # "MKEND" straddled the last two feeds: the held-back bytes came back in order + assert emit == "\nPAYLOAD\n" + assert m.finished + assert m.rc_digits()[1] == 0 + + +def test_marker_split_cmd_and_end_straddle_chunks(): + m = _MarkerSplit("MK") + emit = "" + for chunk in ["echo $__m\"CMD\"; dd ...\r\n", # echoed line: no marker + "M", "KCMD\nDATA", # CMD marker split + "M", "KEND7\n"]: # END marker split + emit += m.feed(chunk) + assert emit == "\nDATA" + assert m.finished + assert m.rc_digits()[1] == 7 + + +def test_base64_sink_decodes_stream_with_noise_and_crs(): + blob = bytes(range(256)) * 41 + armor = base64.b64encode(blob).decode() + # wrap in CRs and prompt noise, feed in awkward small chunks + stream = "\r\n/ # \r\n" + armor + "\r\n" + with tempfile.NamedTemporaryFile(suffix=".part", delete=False) as tf: + path = tf.name + sink = _Base64FileSink(path) + try: + for i in range(0, len(stream), 7): # lines straddle feeds + sink.feed(stream[i:i + 7]) + assert sink.finish() == len(blob) + with open(path, "rb") as f: + assert f.read() == blob + finally: + if os.path.exists(path): + os.unlink(path) + + +def test_base64_sink_rejects_corrupted_payload(): + with tempfile.NamedTemporaryFile(suffix=".part", delete=False) as tf: + path = tf.name + sink = _Base64FileSink(path) + try: + with pytest.raises(Exception): + sink.feed("QUJD\n") # a fine line + sink.feed("ABCDE\n") # passes the charset regex, + sink.finish() # but is not valid base64 + finally: + os.unlink(path) + + +# -- negotiation ---------------------------------------------------------------- + +def _bare_shell(sock): + sh = TelnetShell.__new__(TelnetShell) + sh.sock = sock + sh._carry = b"" + return sh + + +def test_negotiate_handles_iac_straddling_reads(): + a, b = socket.socketpair() + sh = _bare_shell(a) + # IAC DO TTYPE split as [IAC] then [DO TTYPE]; then data + assert sh._negotiate(b"\xff") == b"" + assert sh._negotiate(b"\xfd\x18hello") == b"hello" + # escaped 0xff in data + assert sh._negotiate(b"\xff\xffend") == b"\xffend" + a.close() + b.close() + + +def test_negotiate_sb_frame_split_across_reads(): + a, b = socket.socketpair() + sh = _bare_shell(a) + frame = b"\xff\xfa\x24\x00\x01\x02\xff\xf0tail" + assert sh._negotiate(frame[:5]) == b"" + assert sh._negotiate(frame[5:]) == b"tail" + a.close() + b.close() + + +# -- fake busybox telnet server --------------------------------------------------- + +class FakeBusybox(threading.Thread): + """Speaks a minimal busybox telnetd session over a real socket.""" + + BANNER = b"\r\nBusyBox v1.26.1 built-in shell\r\n" + + def __init__(self, mtd=SMALL_MTD, blobs=b"", good_pass="ivideo", + last_login=False): + super().__init__(daemon=True) + self.good_pass, self.last_login = good_pass, last_login + self.mtd, self.blobs = mtd, blobs + self.sock = socket.socket() + self.sock.bind(("127.0.0.1", 0)) + self.sock.listen(4) + self.port = self.sock.getsockname()[1] + self.start() + + def run(self): + while True: + try: + conn, _ = self.sock.accept() + except OSError: + return + threading.Thread(target=self._serve, args=(conn,), daemon=True).start() + + @staticmethod + def _clean(line): + return IAC_CTRL.sub(b"", line).strip() + + def _recv_line(self, conn, rest): + buf = bytearray(rest) + while b"\n" not in buf: + chunk = conn.recv(4096) + if not chunk: + raise ConnectionError + buf += chunk + line, _, rest = bytes(buf).partition(b"\n") + return self._clean(line), rest + + def _serve(self, conn): + try: + conn.sendall(b"\xff\xfd\x01\r\nlogin: ") + line, rest = self._recv_line(conn, b"") + if line != b"root": + conn.sendall(b"Login incorrect\r\n\r\nlogin: ") + return + conn.sendall(b"Password: ") + line, rest = self._recv_line(conn, rest) + if line != self.good_pass.encode(): + conn.sendall(b"Login incorrect\r\n\r\nlogin: ") + return + if self.last_login: + conn.sendall(b"\r\nLast login: Sun Nov 22 21:00:00 UTC 2026 on pts/0\r\n") + conn.sendall(self.BANNER + b"/ # ") + while True: + line, rest = self._recv_line(conn, rest) + m = re.search(rb"__m=(\w+);", line) + if not m: + continue + marker = m.group(1).decode() + cmd = line.decode() + out = b"" + if "cat /proc/mtd" in cmd: + out, rc = self.mtd.encode(), 0 + elif "dd if=" in cmd: + idx = int(re.search(r"mtd(\d+)ro", cmd).group(1)) + armor = base64.b64encode( + self.blobs.get(idx, b"") if isinstance(self.blobs, dict) + else self.blobs) + # a prompt-noise line before the armor, then wrapped payload + out = b"\r\n/ # \r\n" + armor + b"\r\n" + rc = 0 + elif "false" in cmd: + rc = 1 + else: + rc = 127 + payload = (f"{marker}CMD\n".encode() + out + + f"{marker}END{rc}\n".encode()) + if "dd if=" in cmd: + # fragment the stream deliberately, carrying a complete + # SB subnegotiation frame across the split read boundary + mid = len(payload) // 3 + conn.sendall(payload[:mid] + b"\xff\xfa\x18") + conn.sendall(b"\x01\xff\xf0" + payload[mid:]) + else: + conn.sendall(payload) + conn.sendall(b"/ # ") + except (ConnectionError, OSError): + pass + finally: + try: + conn.close() + except OSError: + pass + + +def _shell(srv, **kw): + return TelnetShell("127.0.0.1", srv.port, user="root", **kw) + + +def test_end_to_end_dump_byte_exact(tmp_path): + blobs = {0: os.urandom(4), 1: os.urandom(16), 2: os.urandom(0x1000)} + srv = FakeBusybox(blobs=blobs) + try: + sh = _shell(srv, password="ivideo") + try: + rc, mtd = sh.run("cat /proc/mtd") + assert rc == 0 and "mtd0" in mtd + parts = parse_proc_mtd(mtd) + assert [p["idx"] for p in parts if not p["ubi"]] == [0, 1, 2] + for p in parts: + if p["ubi"]: + continue + path = str(tmp_path / f"mtd{p['idx']}.bin") + ok, n = dump_partition(sh, p, path) + assert ok and n == p["size"] == len(blobs[p["idx"]]) + with open(path, "rb") as f: + assert f.read() == blobs[p["idx"]] + finally: + sh.close() + finally: + srv.sock.close() + + +def test_logout_failed(): + srv = FakeBusybox() + try: + with pytest.raises(ShellError): + _shell(srv, password="wrong") + finally: + srv.sock.close() + + +def test_last_login_banner_is_not_a_login_failure(): + srv = FakeBusybox(last_login=True) + try: + sh = _shell(srv, password="ivideo") # must not raise + try: + assert sh.run("false")[0] == 1 # rc propagates through the shell + finally: + sh.close() + finally: + srv.sock.close() + + +def test_dump_failure_never_truncates_a_previous_backup(tmp_path): + good = tmp_path / "mtd1-defcfg.bin" + good.write_bytes(b"PREVIOUS GOOD BACKUP" + b"\x00" * 4) + srv = FakeBusybox(blobs={1: os.urandom(0x10 - 1)}) # short by one byte + try: + sh = _shell(srv, password="ivideo") + try: + rc, mtd = sh.run("cat /proc/mtd") + part = [p for p in parse_proc_mtd(mtd) if p["idx"] == 1][0] + with pytest.raises(ShellError): + dump_partition(sh, part, str(good)) + assert good.read_bytes().startswith(b"PREVIOUS GOOD BACKUP") + assert not list(tmp_path.glob("*.part")) + finally: + sh.close() + finally: + srv.sock.close() + + +def test_backup_default_skips_ubi_but_explicit_selects_it(tmp_path): + blobs = {0: os.urandom(4), 1: os.urandom(16), 2: os.urandom(0x1000)} + srv = FakeBusybox(blobs=blobs) + try: + res = backup("127.0.0.1", str(tmp_path), port=srv.port, + user="root", password="ivideo", verbose=False) + assert [r["idx"] for r in res] == [0, 1, 2] # 10-12 skipped + assert not (tmp_path / "mtd12-config.bin").exists() + finally: + srv.sock.close() + + ubi = {12: os.urandom(0x20)} + srv2 = FakeBusybox(blobs=ubi) + try: + out = str(tmp_path / "ubi") + res = backup("127.0.0.1", out, port=srv2.port, user="root", + password="ivideo", parts=[12], verbose=False) + assert len(res) == 1 and res[0]["idx"] == 12 and res[0]["ubi"] + with open(f"{out}/mtd12-config.bin", "rb") as f: + assert f.read() == ubi[12] + finally: + srv2.sock.close() From 5f453afd24d993c65c8ac93be1fc4cbee30cc1f2 Mon Sep 17 00:00:00 2001 From: Dmitry Ilyin <6576495+widgetii@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:09:54 +0300 Subject: [PATCH 3/6] tests: use stdlib unittest, not pytest The CI matrix runs 'python -m unittest discover' with no pytest installed; the nanddump tests were written against pytest and failed import on every matrix job. Mechanically converted (assertRaises, setUp/tearDown lifecycle, tmpdirs cleaned in finally); 42/42 green under both unittest and pytest. --- tests/test_nanddump.py | 356 ++++++++++++++++++++++------------------- 1 file changed, 189 insertions(+), 167 deletions(-) diff --git a/tests/test_nanddump.py b/tests/test_nanddump.py index 55bf183..232f0af 100644 --- a/tests/test_nanddump.py +++ b/tests/test_nanddump.py @@ -1,10 +1,11 @@ """Offline tests for dahua.nanddump: telnet framing, marker/rc handling, base64 stream decoding, /proc/mtd parsing, and a fake busybox end-to-end. -The fake server speaks just enough of a busybox telnet session to exercise -the real client: login prompt(s), an optional "Last login: ..." banner, -marker-framed commands with `dd | base64` payloads, and Telnet control -sequences deliberately split across writes. +stdlib unittest only (the CI runs `python -m unittest discover` without +pytest). The fake server speaks just enough of a busybox telnetd session to +exercise the real client: login prompt(s), an optional "Last login: ..." +banner, marker-framed commands with `dd | base64` payloads, and Telnet +control sequences deliberately split across writes. """ import base64 import os @@ -12,8 +13,7 @@ import socket import tempfile import threading - -import pytest +import unittest from dahua.nanddump import ( TelnetShell, ShellError, _MarkerSplit, _Base64FileSink, parse_proc_mtd, @@ -48,70 +48,65 @@ IAC_CTRL = re.compile(rb"\xff[\xfa-\xfe].") -# -- parsers ------------------------------------------------------------------- - -def test_parse_proc_mtd_tags_ubi_volumes(): - parts = parse_proc_mtd(MTD_TEXT) - assert [p["idx"] for p in parts] == list(range(13)) - assert [p["idx"] for p in parts if p["ubi"]] == [10, 11, 12] - assert parts[3]["size"] == 0x2A00000 - assert [p["idx"] for p in parts if not p["ubi"]] == list(range(10)) - - -def test_marker_split_normal_and_rc(): - m = _MarkerSplit("MK") - emit = m.feed("noise\r\nMKCMD\n") + m.feed("PAYLOAD\nMK") + m.feed("END0\r\n/ # ") - # "MKEND" straddled the last two feeds: the held-back bytes came back in order - assert emit == "\nPAYLOAD\n" - assert m.finished - assert m.rc_digits()[1] == 0 - - -def test_marker_split_cmd_and_end_straddle_chunks(): - m = _MarkerSplit("MK") - emit = "" - for chunk in ["echo $__m\"CMD\"; dd ...\r\n", # echoed line: no marker - "M", "KCMD\nDATA", # CMD marker split - "M", "KEND7\n"]: # END marker split - emit += m.feed(chunk) - assert emit == "\nDATA" - assert m.finished - assert m.rc_digits()[1] == 7 - - -def test_base64_sink_decodes_stream_with_noise_and_crs(): - blob = bytes(range(256)) * 41 - armor = base64.b64encode(blob).decode() - # wrap in CRs and prompt noise, feed in awkward small chunks - stream = "\r\n/ # \r\n" + armor + "\r\n" - with tempfile.NamedTemporaryFile(suffix=".part", delete=False) as tf: - path = tf.name - sink = _Base64FileSink(path) - try: - for i in range(0, len(stream), 7): # lines straddle feeds - sink.feed(stream[i:i + 7]) - assert sink.finish() == len(blob) - with open(path, "rb") as f: - assert f.read() == blob - finally: - if os.path.exists(path): - os.unlink(path) - - -def test_base64_sink_rejects_corrupted_payload(): - with tempfile.NamedTemporaryFile(suffix=".part", delete=False) as tf: - path = tf.name - sink = _Base64FileSink(path) - try: - with pytest.raises(Exception): - sink.feed("QUJD\n") # a fine line - sink.feed("ABCDE\n") # passes the charset regex, - sink.finish() # but is not valid base64 - finally: - os.unlink(path) +class TestParsers(unittest.TestCase): + + def test_parse_proc_mtd_tags_ubi_volumes(self): + parts = parse_proc_mtd(MTD_TEXT) + self.assertEqual([p["idx"] for p in parts], list(range(13))) + self.assertEqual([p["idx"] for p in parts if p["ubi"]], [10, 11, 12]) + self.assertEqual(parts[3]["size"], 0x2A00000) + self.assertEqual([p["idx"] for p in parts if not p["ubi"]], + list(range(10))) + + def test_marker_split_normal_and_rc(self): + m = _MarkerSplit("MK") + emit = m.feed("noise\r\nMKCMD\n") + m.feed("PAYLOAD\nMK") \ + + m.feed("END0\r\n/ # ") + # "MKEND" straddled the last two feeds: held-back bytes came back in order + self.assertEqual(emit, "\nPAYLOAD\n") + self.assertTrue(m.finished) + self.assertEqual(m.rc_digits()[1], 0) + + def test_marker_split_cmd_and_end_straddle_chunks(self): + m = _MarkerSplit("MK") + emit = "" + for chunk in ["echo $__m\"CMD\"; dd ...\r\n", # echoed line: no marker + "M", "KCMD\nDATA", # CMD marker split + "M", "KEND7\n"]: # END marker split + emit += m.feed(chunk) + self.assertEqual(emit, "\nDATA") + self.assertTrue(m.finished) + self.assertEqual(m.rc_digits()[1], 7) + + def test_base64_sink_decodes_stream_with_noise_and_crs(self): + blob = bytes(range(256)) * 41 + armor = base64.b64encode(blob).decode() + stream = "\r\n/ # \r\n" + armor + "\r\n" + with tempfile.NamedTemporaryFile(suffix=".part", delete=False) as tf: + path = tf.name + try: + sink = _Base64FileSink(path) + for i in range(0, len(stream), 7): # lines straddle feeds + sink.feed(stream[i:i + 7]) + self.assertEqual(sink.finish(), len(blob)) + with open(path, "rb") as f: + self.assertEqual(f.read(), blob) + finally: + if os.path.exists(path): + os.unlink(path) + def test_base64_sink_rejects_corrupted_payload(self): + with tempfile.NamedTemporaryFile(suffix=".part", delete=False) as tf: + path = tf.name + sink = _Base64FileSink(path) + try: + with self.assertRaises(Exception): + sink.feed("QUJD\n") # a fine line + sink.feed("ABCDE\n") # passes the charset + sink.finish() # regex, not valid base64 + finally: + os.unlink(path) -# -- negotiation ---------------------------------------------------------------- def _bare_shell(sock): sh = TelnetShell.__new__(TelnetShell) @@ -120,29 +115,30 @@ def _bare_shell(sock): return sh -def test_negotiate_handles_iac_straddling_reads(): - a, b = socket.socketpair() - sh = _bare_shell(a) - # IAC DO TTYPE split as [IAC] then [DO TTYPE]; then data - assert sh._negotiate(b"\xff") == b"" - assert sh._negotiate(b"\xfd\x18hello") == b"hello" - # escaped 0xff in data - assert sh._negotiate(b"\xff\xffend") == b"\xffend" - a.close() - b.close() - +class TestNegotiate(unittest.TestCase): -def test_negotiate_sb_frame_split_across_reads(): - a, b = socket.socketpair() - sh = _bare_shell(a) - frame = b"\xff\xfa\x24\x00\x01\x02\xff\xf0tail" - assert sh._negotiate(frame[:5]) == b"" - assert sh._negotiate(frame[5:]) == b"tail" - a.close() - b.close() + def test_iac_straddling_reads(self): + a, b = socket.socketpair() + try: + sh = _bare_shell(a) + self.assertEqual(sh._negotiate(b"\xff"), b"") + self.assertEqual(sh._negotiate(b"\xfd\x18hello"), b"hello") + self.assertEqual(sh._negotiate(b"\xff\xffend"), b"\xffend") + finally: + a.close() + b.close() + def test_sb_frame_split_across_reads(self): + a, b = socket.socketpair() + try: + sh = _bare_shell(a) + frame = b"\xff\xfa\x24\x00\x01\x02\xff\xf0tail" + self.assertEqual(sh._negotiate(frame[:5]), b"") + self.assertEqual(sh._negotiate(frame[5:]), b"tail") + finally: + a.close() + b.close() -# -- fake busybox telnet server --------------------------------------------------- class FakeBusybox(threading.Thread): """Speaks a minimal busybox telnetd session over a real socket.""" @@ -166,7 +162,8 @@ def run(self): conn, _ = self.sock.accept() except OSError: return - threading.Thread(target=self._serve, args=(conn,), daemon=True).start() + threading.Thread(target=self._serve, args=(conn,), + daemon=True).start() @staticmethod def _clean(line): @@ -195,7 +192,8 @@ def _serve(self, conn): conn.sendall(b"Login incorrect\r\n\r\nlogin: ") return if self.last_login: - conn.sendall(b"\r\nLast login: Sun Nov 22 21:00:00 UTC 2026 on pts/0\r\n") + conn.sendall(b"\r\nLast login: Sun Nov 22 21:00:00 UTC 2026" + b" on pts/0\r\n") conn.sendall(self.BANNER + b"/ # ") while True: line, rest = self._recv_line(conn, rest) @@ -210,9 +208,9 @@ def _serve(self, conn): elif "dd if=" in cmd: idx = int(re.search(r"mtd(\d+)ro", cmd).group(1)) armor = base64.b64encode( - self.blobs.get(idx, b"") if isinstance(self.blobs, dict) - else self.blobs) - # a prompt-noise line before the armor, then wrapped payload + self.blobs.get(idx, b"") + if isinstance(self.blobs, dict) else self.blobs) + # a prompt-noise line, then the armored payload out = b"\r\n/ # \r\n" + armor + b"\r\n" rc = 0 elif "false" in cmd: @@ -243,89 +241,113 @@ def _shell(srv, **kw): return TelnetShell("127.0.0.1", srv.port, user="root", **kw) -def test_end_to_end_dump_byte_exact(tmp_path): - blobs = {0: os.urandom(4), 1: os.urandom(16), 2: os.urandom(0x1000)} - srv = FakeBusybox(blobs=blobs) - try: - sh = _shell(srv, password="ivideo") +class TestEndToEnd(unittest.TestCase): + + def setUp(self): + self.servers = [] + + def tearDown(self): + for srv in self.servers: + srv.sock.close() + + def _server(self, **kw): + srv = FakeBusybox(**kw) + self.servers.append(srv) + return srv + + def test_dump_byte_exact(self): + import shutil + tmp = tempfile.mkdtemp() try: - rc, mtd = sh.run("cat /proc/mtd") - assert rc == 0 and "mtd0" in mtd - parts = parse_proc_mtd(mtd) - assert [p["idx"] for p in parts if not p["ubi"]] == [0, 1, 2] - for p in parts: - if p["ubi"]: - continue - path = str(tmp_path / f"mtd{p['idx']}.bin") - ok, n = dump_partition(sh, p, path) - assert ok and n == p["size"] == len(blobs[p["idx"]]) - with open(path, "rb") as f: - assert f.read() == blobs[p["idx"]] + blobs = {0: os.urandom(4), 1: os.urandom(16), 2: os.urandom(0x1000)} + srv = self._server(blobs=blobs) + sh = _shell(srv, password="ivideo") + try: + rc, mtd = sh.run("cat /proc/mtd") + self.assertEqual(rc, 0) + self.assertIn("mtd0", mtd) + parts = parse_proc_mtd(mtd) + self.assertEqual([p["idx"] for p in parts if not p["ubi"]], + [0, 1, 2]) + for p in parts: + if p["ubi"]: + continue + path = os.path.join(tmp, f"mtd{p['idx']}.bin") + ok, n = dump_partition(sh, p, path) + self.assertTrue(ok) + self.assertEqual(n, p["size"]) + self.assertEqual(n, len(blobs[p["idx"]])) + with open(path, "rb") as f: + self.assertEqual(f.read(), blobs[p["idx"]]) + finally: + sh.close() finally: - sh.close() - finally: - srv.sock.close() - + shutil.rmtree(tmp, ignore_errors=True) -def test_logout_failed(): - srv = FakeBusybox() - try: - with pytest.raises(ShellError): + def test_logout_failed(self): + srv = self._server() + with self.assertRaises(ShellError): _shell(srv, password="wrong") - finally: - srv.sock.close() - -def test_last_login_banner_is_not_a_login_failure(): - srv = FakeBusybox(last_login=True) - try: - sh = _shell(srv, password="ivideo") # must not raise + def test_last_login_banner_is_not_a_login_failure(self): + srv = self._server(last_login=True) + sh = _shell(srv, password="ivideo") # must not raise try: - assert sh.run("false")[0] == 1 # rc propagates through the shell + self.assertEqual(sh.run("false")[0], 1) finally: sh.close() - finally: - srv.sock.close() + def test_dump_failure_never_truncates_a_previous_backup(self): + import shutil + tmp = tempfile.mkdtemp() + try: + good = os.path.join(tmp, "mtd1-defcfg.bin") + with open(good, "wb") as f: + f.write(b"PREVIOUS GOOD BACKUP" + b"\x00" * 4) + srv = self._server(blobs={1: os.urandom(0x10 - 1)}) # short by one + sh = _shell(srv, password="ivideo") + try: + rc, mtd = sh.run("cat /proc/mtd") + part = [p for p in parse_proc_mtd(mtd) if p["idx"] == 1][0] + with self.assertRaises(ShellError): + dump_partition(sh, part, good) + with open(good, "rb") as f: + self.assertTrue(f.read().startswith(b"PREVIOUS GOOD BACKUP")) + self.assertEqual([], [n for n in os.listdir(tmp) + if n.endswith(".part")]) + finally: + sh.close() + finally: + shutil.rmtree(tmp, ignore_errors=True) + + def test_backup_default_skips_ubi_but_explicit_selects_it(self): + import shutil + tmp = tempfile.mkdtemp() + try: + blobs = {0: os.urandom(4), 1: os.urandom(16), 2: os.urandom(0x1000)} + srv = self._server(blobs=blobs) + res = backup("127.0.0.1", tmp, port=srv.port, user="root", + password="ivideo", verbose=False) + self.assertEqual([r["idx"] for r in res], [0, 1, 2]) # 10-12 skip + self.assertFalse(os.path.exists( + os.path.join(tmp, "mtd12-config.bin"))) + finally: + shutil.rmtree(tmp, ignore_errors=True) -def test_dump_failure_never_truncates_a_previous_backup(tmp_path): - good = tmp_path / "mtd1-defcfg.bin" - good.write_bytes(b"PREVIOUS GOOD BACKUP" + b"\x00" * 4) - srv = FakeBusybox(blobs={1: os.urandom(0x10 - 1)}) # short by one byte - try: - sh = _shell(srv, password="ivideo") + tmp2 = tempfile.mkdtemp() try: - rc, mtd = sh.run("cat /proc/mtd") - part = [p for p in parse_proc_mtd(mtd) if p["idx"] == 1][0] - with pytest.raises(ShellError): - dump_partition(sh, part, str(good)) - assert good.read_bytes().startswith(b"PREVIOUS GOOD BACKUP") - assert not list(tmp_path.glob("*.part")) + ubi = {12: os.urandom(0x20)} + srv2 = self._server(blobs=ubi) + res = backup("127.0.0.1", tmp2, port=srv2.port, user="root", + password="ivideo", parts=[12], verbose=False) + self.assertEqual(len(res), 1) + self.assertEqual(res[0]["idx"], 12) + self.assertTrue(res[0]["ubi"]) + with open(os.path.join(tmp2, "mtd12-config.bin"), "rb") as f: + self.assertEqual(f.read(), ubi[12]) finally: - sh.close() - finally: - srv.sock.close() - - -def test_backup_default_skips_ubi_but_explicit_selects_it(tmp_path): - blobs = {0: os.urandom(4), 1: os.urandom(16), 2: os.urandom(0x1000)} - srv = FakeBusybox(blobs=blobs) - try: - res = backup("127.0.0.1", str(tmp_path), port=srv.port, - user="root", password="ivideo", verbose=False) - assert [r["idx"] for r in res] == [0, 1, 2] # 10-12 skipped - assert not (tmp_path / "mtd12-config.bin").exists() - finally: - srv.sock.close() - - ubi = {12: os.urandom(0x20)} - srv2 = FakeBusybox(blobs=ubi) - try: - out = str(tmp_path / "ubi") - res = backup("127.0.0.1", out, port=srv2.port, user="root", - password="ivideo", parts=[12], verbose=False) - assert len(res) == 1 and res[0]["idx"] == 12 and res[0]["ubi"] - with open(f"{out}/mtd12-config.bin", "rb") as f: - assert f.read() == ubi[12] - finally: - srv2.sock.close() + shutil.rmtree(tmp2, ignore_errors=True) + + +if __name__ == "__main__": + unittest.main() From eb98f1c83f189e0c98dbdfede20570c59a665d3c Mon Sep 17 00:00:00 2001 From: Dmitry Ilyin <6576495+widgetii@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:11:29 +0300 Subject: [PATCH 4/6] ci: drop EOL Python 3.9 from the test matrix actions/setup-python cannot install 3.9 on ubuntu-latest anymore (Ubuntu 26.04 has no 3.9 build; 3.9 is EOL since 2025-10), so every current PR fails on that matrix row before running a single test. Remove the 3.9 row; 3.10-3.13 keep running the suite. pyproject still declares >=3.9 and the code remains 3.9-compatible (future annotations, verified syntax) -- it just cannot be CI-tested on the current runner image. --- .github/workflows/ci.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b27b0ea..3c23672 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,7 +11,11 @@ jobs: strategy: fail-fast: false matrix: - python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] + # 3.9 dropped: it is EOL and actions/setup-python can no longer + # install it on ubuntu-latest (Ubuntu 26.04). The code still + # targets >=3.9 (future annotations); it is just not testable + # on the current runner image. + python-version: ["3.10", "3.11", "3.12", "3.13"] steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} From 63f3c548d786b1781285f94bd0464f55e818273f Mon Sep 17 00:00:00 2001 From: Dmitry Ilyin <6576495+widgetii@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:12:33 +0300 Subject: [PATCH 5/6] ci: pin the 3.9 job to ubuntu-24.04 instead of dropping it "test (3.9)" is a required status check in branch protection, so removing the row blocks the merge forever (the check can never report). Keep the row and pin it to the last runner image with a published 3.9 build (actions/python-versions 3.9.25 ships 22.04/24.04, not 26.04); 3.10-3.13 stay on ubuntu-latest. CI coverage of 3.9 is restored instead of abandoned. --- .github/workflows/ci.yml | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3c23672..2f5cba3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,15 +7,25 @@ on: jobs: test: - runs-on: ubuntu-latest strategy: fail-fast: false matrix: - # 3.9 dropped: it is EOL and actions/setup-python can no longer - # install it on ubuntu-latest (Ubuntu 26.04). The code still - # targets >=3.9 (future annotations); it is just not testable - # on the current runner image. - python-version: ["3.10", "3.11", "3.12", "3.13"] + include: + # 3.9 is EOL and has no build for ubuntu-latest (Ubuntu 26.04), + # so its row is pinned to the last runner image that ships one. + # The job name must stay "test (3.9)": it is a required status + # check in branch protection. + - python-version: "3.9" + runner: ubuntu-24.04 + - python-version: "3.10" + runner: ubuntu-latest + - python-version: "3.11" + runner: ubuntu-latest + - python-version: "3.12" + runner: ubuntu-latest + - python-version: "3.13" + runner: ubuntu-latest + runs-on: ${{ matrix.runner }} steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} From 386f4242b4c11ad6da1fa2b4e246ecd8f4d0e089 Mon Sep 17 00:00:00 2001 From: Dmitry Ilyin <6576495+widgetii@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:13:19 +0300 Subject: [PATCH 6/6] ci: pin the 3.9 job name so the required check matches With a matrix.include that adds a second key (runner), the display name auto-expands to 'test (3.9, ubuntu-24.04)' and the required status check 'test (3.9)' is never satisfied. Set the job name explicitly to 'test (${{ matrix.python-version }})' so all rows report under the exact names branch protection expects. --- .github/workflows/ci.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2f5cba3..359cb28 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,6 +7,7 @@ on: jobs: test: + name: test (${{ matrix.python-version }}) strategy: fail-fast: false matrix: @@ -14,7 +15,10 @@ jobs: # 3.9 is EOL and has no build for ubuntu-latest (Ubuntu 26.04), # so its row is pinned to the last runner image that ships one. # The job name must stay "test (3.9)": it is a required status - # check in branch protection. + # check in branch protection. Hence the explicit job `name` + # above -- the auto-generated matrix name would otherwise + # include the runner ("test (3.9, ubuntu-24.04)") and the + # required check would never be satisfied. - python-version: "3.9" runner: ubuntu-24.04 - python-version: "3.10"