diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b27b0ea..359cb28 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,11 +7,29 @@ on: jobs: test: - runs-on: ubuntu-latest + name: test (${{ matrix.python-version }}) strategy: fail-fast: false matrix: - python-version: ["3.9", "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. 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" + 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 }} 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..af8502c 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,74 @@ 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 + # 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: + 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) + 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: + 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()) + 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.", + 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 +323,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..b69c575 --- /dev/null +++ b/dahua/nanddump.py @@ -0,0 +1,370 @@ +"""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 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. +""" +from __future__ import annotations + +import base64 +import os +import re +import socket +import sys +import time + +IAC, DONT, DO, WONT, WILL, SB, SE = 255, 254, 253, 252, 251, 250, 240 + + +class ShellError(RuntimeError): + pass + + +class TelnetShell: + """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) + 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, n = 0, len(data) + while i < n: + b = data[i] + 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 + 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: + 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(nd in buf for nd in needles): + break + continue + if not chunk: + break + buf += self._negotiate(chunk) + 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') + 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 split.finished: + break + continue + if not chunk: + 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: + split.feed(self._negotiate(self.sock.recv(4096)) + .decode(errors="replace")) + except socket.timeout: + pass + break + idle = time.time() + timeout # got data: reset the idle clock + return split.rc_digits()[1] if split.rc_digits() else -1 + + def close(self) -> None: + try: + self._send("exit\n") + self.sock.close() + except OSError: + 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]: + """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 = int(m.group(1)), int(m.group(2), 16), int(m.group(3), 16) + if raw_erase is None: + raw_erase = erase + 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). + + 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" + 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: + 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 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") + 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 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)) + os.makedirs(outdir, exist_ok=True) + result = [] + for p in todo: + path = f"{outdir}/mtd{p['idx']}-{p['name']}.bin" + t0 = time.time() + _, n = dump_partition(shell, p, path) + dt = time.time() - t0 + result.append({**p, "file": path, "ok": True, "bytes": n}) + if verbose: + print(f"[OK ] {path} {n}/{p['size']} bytes " + f"{n / max(dt, 0.001) / 1024:.0f} KiB/s", file=sys.stderr) + return result + finally: + shell.close() diff --git a/tests/test_nanddump.py b/tests/test_nanddump.py new file mode 100644 index 0000000..232f0af --- /dev/null +++ b/tests/test_nanddump.py @@ -0,0 +1,353 @@ +"""Offline tests for dahua.nanddump: telnet framing, marker/rc handling, +base64 stream decoding, /proc/mtd parsing, and a fake busybox end-to-end. + +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 +import re +import socket +import tempfile +import threading +import unittest + +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].") + + +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) + + +def _bare_shell(sock): + sh = TelnetShell.__new__(TelnetShell) + sh.sock = sock + sh._carry = b"" + return sh + + +class TestNegotiate(unittest.TestCase): + + 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() + + +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" + b" 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, then the armored 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) + + +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: + 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: + shutil.rmtree(tmp, ignore_errors=True) + + def test_logout_failed(self): + srv = self._server() + with self.assertRaises(ShellError): + _shell(srv, password="wrong") + + 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: + self.assertEqual(sh.run("false")[0], 1) + finally: + sh.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) + + tmp2 = tempfile.mkdtemp() + try: + 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: + shutil.rmtree(tmp2, ignore_errors=True) + + +if __name__ == "__main__": + unittest.main()